关于shell:在MAC上用Python调用Popen – 错误无法找到文件

Calling Popen in Python on a MAC - Error can not find file

当我试图从python 3.51程序中解包以运行popen命令时,我得到了以下错误。然而,当我将传递给popen的字符串复制到终端命令行时,它可以正常工作,并在adobe reader中打开文件,这是我的.pdf文件的默认应用程序。

代码如下:

1
2
3
  finalCall = r'open /Users/gbarnabic/Documents/1111/combined.pdf'
    print(finalCall)
    pid_id = subprocess.Popen(finalCall).pid

错误如下:

open /Users/gbarnabic/Documents/1111/combined.pdf
Exception in Tkinter callback
Traceback (most recent call last):
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/init.py", line 1549, in call
return self.func(*args)
File"pdfcomb2.py", line 212, in change_dir
self.openPDF(outFileName, pageNum)
File"pdfcomb2.py", line 426, in openPDF
subprocess.run(finalCall)
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 696, in run
with Popen(*popenargs, **kwargs) as process:
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in init
restore_signals, start_new_session)
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'open /Users/gb/Documents/1111/combined.pdf'
Georges-MBP:filepicktest gb$ open /Users/gb/Documents/1111/combined.pdf
Georges-MBP:filepicktest gb$


使用popen,需要设置shell=True以将命令作为字符串或拆分命令在参数列表中传递。可以用shlex完成

1
2
3
import shlex
import subprocess
subprocess.Popen(shlex.split('open ....'))

您可以查看文档中的示例:https://docs.python.org/2/library/subprocess.html subprocess.popen

所以这里的错误意味着python试图运行名为open /Users/gb/Documents/1111/combined.pdf的文件。显然它不存在