python - subprocess.Popen 使用相对路径

标签 python path subprocess popen cwd

docs对于 Popen,您不能指定相对于“更改工作目录”kwarg 的可执行文件路径。

If cwd is not None, the child’s current directory will be changed to cwd 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 to cwd.

但 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/

相关文章:

python - subprocess ssh 命令对某些命令失败但对其他命令失败(命令在终端中运行)

Python subprocess.check_output 输出与同一命令的 bash 输出不同

python - CSRF 验证不适用于使用 HTTPS 的 Django

python - 腐败的可能性 : Reading Excel Files with Pandas

java - 如何正确修补 JAR 文件中的 Java 类?

java - 检查路径是否代表文件或文件夹

python - 从堆栈跟踪到树

python - 使用 Python 的命令行

java - 给定特定步数从起始节点到结束节点的最大路径

python - 在python中执行两行以上的bash代码