Popen的docs提到不能指定相对于“change working directory”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在我的系统上的行为似乎与这一说法直接矛盾:
wim@SDFA100461C:/tmp$ mkdir a
wim@SDFA100461C:/tmp$ cp /bin/ls /tmp/a/my_ls
wim@SDFA100461C:/tmp$ mkdir b
wim@SDFA100461C:/tmp$ touch /tmp/b/potato
wim@SDFA100461C:/tmp$ cd /home/wim
wim@SDFA100461C:~$ 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
使用相对路径是否与平台相关且不应依赖?或者这是一个文档错误?在
(这个问题来自glglglglglglglglglhere的评论)
是的,这取决于平台。在
在POSIX系统上,进程是分叉的,在子进程中,
os.chdir(cwd)
在执行可执行文件之前执行。在但是在Windows上,使用^{} API call ,并且
cwd
作为lpCurrentDirectory
参数传入。不会发生目录更改,CreateProcess()
调用在查找要执行的lpApplicationName
时会参考该参数。在要使应用程序跨平台,在查找可执行文件时,不应依赖于要更改的当前工作目录。在
相关问题 更多 >
编程相关推荐