[Python] Popen error: [Errno 2] No such file or directory

遇到使用 subprocess.Popen(path) 顯示錯誤:

Popen error: [Errno 2] No such file or directory

雖然有人說可以設定 cwd 參數給 Popen 但還是一樣會出錯。

解法:

shell=True was likely the correct solution to the o.p., since they did not make the following mistake, but you can also get the “No such file or directory” error if you do not split up your executable from its arguments.

import subprocess as sp, shlex
sp.Popen(['echo 1']) # FAILS with "No such file or directory"
sp.Popen(['echo', '1']) # SUCCEEDS
sp.Popen(['echo 1'], shell=True) # SUCCEEDS, but extra overhead
sp.Popen(shlex.split('echo 1')) # SUCCEEDS, equivalent to #2

Without shell=True, Popen expects the executable to be the first element of args, which is why it fails, there is no “echo 1” executable. Adding shell=True invokes your system shell and passes the first element of args to the shell. i.e. for linux, Popen(['echo 1'], shell=True) is equivalent to Popen('/bin/sh', '-c', 'echo 1') which is more overhead than you may need. See Popen() documentation for cases when shell=True is actually useful.


相關文章:

python 呼叫外部指令
http://stackoverflow.max-everyday.com/2017/09/python-subprocess/

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *