子流程.Popen使用相对路径

2024-06-09 13:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

Popen的docs提到不能指定相对于“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.

但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的评论)


Tags: thetooutputismychecknotls
1条回答
网友
1楼 · 发布于 2024-06-09 13:18:29

是的,这取决于平台。在

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

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

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

相关问题 更多 >