英文:
String to clipboard, but without the new line?
问题
工作在一个需要将字符串复制到剪贴板以供用户在其他应用程序中使用的Python项目中。目前我有以下代码:
os.system(f"echo {phrase}| clip")
目前在Python控制台中运行正常,但每当我使用Ctrl+V/右键+粘贴功能时,它会粘贴{phrase},但还会在其下方包括一个新行,这会影响其他应用程序。
我已经尝试在{phrase}上使用str.strip()和str.rstrip(),但没有任何效果。任何帮助将不胜感激。
英文:
Working on a python project where I need to copy a string to the clipboard for the user to use on other applications based on inputs. Right now I have the following:
os.system(f"echo {phrase}| clip")
for now it works fine within the python console, but whenever I do a ctrl+v/right-click+paste function it will paste the {phrase} but also include a new line right below it which throws off the other applications.
I've tried using str.strip() and str.rstrip() on {phrase} but it doesn't make a difference. Any help would be appreciated.
答案1
得分: 5
问题是echo默认会打印一个换行符;添加-n开关来防止它打印换行符。
然而,不要这样做:
os.system(f"echo -n {phrase} | clip")
因为如果phrase包含恶意用户输入,你就会面临(远程)代码执行漏洞(考虑| somethingevil)。
相反,使用subprocess.run()和input,它会执行与从echo到clip的管道相同的操作,而你根本不需要echo。
subprocess.run("clip", input=phrase, check=True, encoding="utf-8")
更好的方法是,你可以使用pyperclip 模块:
pyperclip.copy('要复制到剪贴板的文本。')
英文:
The issue is echo prints out a newline by default; add the -n switch to make it not to.
HOWEVER, DON'T DO THIS:
os.system(f"echo -n {phrase} | clip")
because if phrase contains malicious user input, you've got a (remote) code execution vulnerability at your hands (consider | somethingevil).
Instead, use subprocess.run() with input, which does the same as piping from echo to clip, and you don't need echo at all.
subprocess.run("clip", input=phrase, check=True, encoding="utf-8")
Better still, you could use the pyperclip module:
pyperclip.copy('The text to be copied to the clipboard.')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论