【发布时间】: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 activateosascript -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.system 与 subprocess.Popen 的底层机制。
【问题讨论】:
标签: python windows macos python-2.7