字符串复制到剪贴板,但不包含换行符?

huangapple go评论93阅读模式
英文:

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,它会执行与从echoclip的管道相同的操作,而你根本不需要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.')

huangapple
  • 本文由 发表于 2023年3月10日 01:45:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75688256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定