10

The docs for Popen mention that you can't specify your executable path relative to the 'change working directory' 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.

But python's behaviour on my system seems to directly contradict this claim:

/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

Is using relative paths to cwd something that is platform dependent and shouldn't be relied upon? Or is this a documentation bug?

(this question spawns from a comment by glglgl here)

4

1 回答 1

13

是的,这取决于平台。

在 POSIX 系统上,进程是分叉的,并且在子进程中 aos.chdir(cwd)在执行可执行文件之前执行。

然而,在 Windows 上,CreateProcess()API 调用被使用并作为参数cwd传入。lpCurrentDirectory不会发生目录更改,并且在查找要执行的时CreateProcess()调用不会参考该参数lpApplicationName

为了让您的应用程序跨平台,您在查找可执行文件时不应依赖于更改当前工作目录。

于 2014-01-28T17:36:25.410 回答