docs对于 Popen,您不能指定相对于“更改工作目录”kwarg 的可执行文件路径。
If
cwd
is not None, the child’s current directory will be changed tocwd
before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative tocwd
.
但 python 在我的系统上的行为似乎直接与这种说法相矛盾:
/tmp$ mkdir a
/tmp$ cp /bin/ls /tmp/a/my_ls
/tmp$ mkdir b
/tmp$ touch /tmp/b/potato
/tmp$ cd /home/wim
~$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import check_output
>>> check_output(['../a/my_ls'], cwd='/tmp/b')
'potato\n'
>>> check_output(['../a/my_ls'])
OSError: [Errno 2] No such file or directory
是否使用到 cwd
的相对路径依赖于平台并且不应依赖?或者这是文档错误?
(这个问题源自 glglgl here 的评论)
最佳答案
是的,这取决于平台。
在 POSIX 系统上,进程被派生,在执行可执行文件之前,在子进程中执行 os.chdir(cwd)
。
然而,在 Windows 上,CreateProcess()
API call使用 cwd
作为 lpCurrentDirectory
参数传入。没有发生目录更改,CreateProcess()
调用在查找要执行的 lpApplicationName
时不引用该参数。
为了让您的应用程序保持跨平台,在查找可执行文件时,您不应依赖于更改当前工作目录。
关于python - subprocess.Popen 使用相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412610/