【问题标题】:Python: Trouble with cross platform running of subprocessesPython:跨平台运行子进程的问题
【发布时间】:2016-09-08 14:49:38
【问题描述】:

我有以下辅助方法,它可以在 OSX 上完美执行命令,并且只能在 Windows 上使用一些命令:

def exec_cmd(cmd):
    """Run a command and return the status, standard output and error."""
    proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    # I like to get True or False rather than 0 (True) or 1 (False)
    # which is just backwards as usually 0 is False and 1 is True
    status = not bool(proc.returncode)
    return (status, stdout, stderr)

例如,以下示例命令都可以使用我的 exec_cmd 助手在 Mac 上完美运行:

  • osascript -e 'tell application "Microsoft PowerPoint" to activate
  • osascript -e 'tell application "Microsoft PowerPoint" to quit

例如,以下示例命令都可以使用我的 exec_cmd 助手在 Windows 上完美运行:

  • "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe" /S "C:\Users\MyUser\example.pptx"
  • Taskkill /IM POWERPNT.EXE /F

但是,以下内容在 Windows 上不起作用:

  • START "" "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe"

它出错了:

WindowsError: [Error 2] The system cannot find the file specified

即使这样也行不通:

p = Popen(["START", "", "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe"], stdout=PIPE, stderr=PIPE)

但是在命令行上运行相同的命令可以正常工作,甚至陌生人只是这样做也可以:

os.system('START "" "C:\Program Files\Microsoft Office\Office15\Powerpnt.exe"')

为什么 os.system 可以工作,而 Popen 版本不行?这些只是简单的打开和关闭应用程序示例,但我想做更多,因为我需要为我计划运行的一些命令获取标准输出输出。

感谢您对解决此问题的任何帮助。我似乎无法理解 os.systemsubprocess.Popen 的底层机制。

【问题讨论】:

    标签: python windows macos python-2.7


    【解决方案1】:

    您看到这个问题是因为START 不是程序,它是一个 shell 命令。根据文档,os.system()“在子shell 中执行命令(字符串)”,而popen 没有。 os.system() 有效地生成了一个新的 cmd.exe 实例,并将命令传递给该实例,而 popen 只是生成了一个新进程。

    您收到 The system cannot find the file specified 错误,因为没有名为 START 的程序

    【讨论】:

    • 天啊。你说得对。我是个白痴。我想这就是为什么要为这个 Popen 命令传递可怕的 shell=True ,它可以在 Windows 上运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多