【问题标题】:Escaping string arugments to subprocess calls in Windows将字符串参数转义到 Windows 中的子进程调用
【发布时间】:2015-04-28 00:29:49
【问题描述】:

为什么Example onehello 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"

那么,如何将多行文本复制到剪贴板而不使用双引号?

【问题讨论】:

  • 我不知道您为什么要为此使用 cmd shell;这很头疼。你可以简单地使用p = Popen('clip.exe', stdin=PIPE, stdout=PIPE, universal_newlines=True);p.communicate('hello\nworld');p.wait()
  • @eryksun 你为什么不回答这个问题?!我不喜欢 cmd shell。我必须需要它才能工作。
  • 我并没有真正回答这个问题,而是避免它。每当我认为我掌握了 cmd.exe 将如何解析命令行时,我就会被烧毁。

标签: windows python-3.x subprocess clipboard


【解决方案1】:

正如@eryksun 所建议的,这解决了这个问题:

p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()

【讨论】:

    【解决方案2】:

    我怀疑这是因为您使用的是shell=True,请重构您的代码以不使用它。

    但我建议完全放弃这种方法并使用pyperclip 来支持剪贴板。它是跨平台的并且免费提供。

    【讨论】:

    • 不,它根本不起作用。 FileNotFoundError: [WinError 2] The system cannot find the file specified
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多