简体   繁体   中英

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

When I try to shell out of my Python 3.51 program to run the Popen command I get the following errors. Yet when I copy the exact string I'm passing to Popen to the Terminal command line it works fine and opens the file in Adobe Reader which is my default app for the .pdf files.

Here is the Code:

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

Here is the error:

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/1 111/combined.pdf Georges-MBP:filepicktest gb$

With Popen you need to set shell=True to pass command as a string or split command in a list of arguments. Could be done with shlex

import shlex
import subprocess
subprocess.Popen(shlex.split('open ....'))

You could check example in documentation: https://docs.python.org/2/library/subprocess.html#subprocess.Popen

So the error here means that Python try to run file with name open /Users/gb/Documents/1111/combined.pdf . Obviously it doesn't exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM