我正在尝试使用python subprocess
包运行命令。我已经在Ubuntu机器上将编译后的可执行文件的路径添加到了我的PATH
。
当我这样做时,它的工作原理:
myexecutable input_file output_file
当我这样做时,它的工作原理:
import subprocess
import shlex
cmd = '/path/to/my/myexecutable input_file output_file'
subprocess.Popen(shlex.split(cmd))
这是踢球者。当我这样做时,它不起作用:
import subprocess
import shlex
cmd = 'myexecutable input_file output_file'
subprocess.Popen(shlex.split(cmd))
它给了我:
OSError Traceback (most recent call last)
<ipython-input-4-8f5c3da8b0a3> in <module>()
----> 1 subprocess.call(shlex.split(cmd))
/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in call(*popenargs, **kwargs)
170 retcode = call(["ls", "-l"])
171 """
--> 172 return Popen(*popenargs, **kwargs).wait()
173
174
/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
392 p2cread, p2cwrite,
393 c2pread, c2pwrite,
--> 394 errread, errwrite)
395 except Exception:
396 # Preserve original exception in case os.close raises.
/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
1045 raise
1046 child_exception = pickle.loads(data)
-> 1047 raise child_exception
1048
1049
OSError: [Errno 2] No such file or directory
是什么赋予了?
无论你使用什么样的shell(以及subprocess.Popen(..., shell=True)
,但附带警告)都会根据PATH
环境变量计算出实际的可执行文件。
subprocess.Popen()
本身没有。在UNIX系统上解决此问题的一种常用方法(即在路径查找中进行)是使用广泛使用的/usr/bin/env
工具进行相同的扩展,即
subprocess.Popen(['/usr/bin/env', 'mytool', 'hurr', 'durr'])
但这不适合Windows。
处理事情的最好方法是自己进行查找,即找出可执行文件的完整路径并将其传递给subprocess.Popen()
- os.path.realpath()
可能是您的朋友。