将字符串参数转义到 Windows 中的子进程调用
Escaping string arugments to subprocess calls in Windows
为什么 Example one
将 hello world
复制到我的剪贴板而不是 Example two
?
# Example one
subprocess.check_output(["echo", "hello world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)
# Example two
subprocess.check_output(["echo", "hello \n world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)
另一个问题是 Example one
像这样复制 hello world 并在其周围加上引号:
"hello world"
那么,如何将不带双引号的多行文本复制到剪贴板?
我怀疑是因为您正在使用 shell=True
,重构您的代码以不使用它。
但我建议完全放弃这种方法并使用 pyperclip 支持剪贴板。它是跨平台的并且可以免费使用。
根据@eryksun 的建议,这解决了问题:
p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()
为什么 Example one
将 hello world
复制到我的剪贴板而不是 Example two
?
# Example one
subprocess.check_output(["echo", "hello world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)
# Example two
subprocess.check_output(["echo", "hello \n world", "|", "clip"], shell=True, stderr=subprocess.STDOUT)
另一个问题是 Example one
像这样复制 hello world 并在其周围加上引号:
"hello world"
那么,如何将不带双引号的多行文本复制到剪贴板?
我怀疑是因为您正在使用 shell=True
,重构您的代码以不使用它。
但我建议完全放弃这种方法并使用 pyperclip 支持剪贴板。它是跨平台的并且可以免费使用。
根据@eryksun 的建议,这解决了问题:
p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()