subprocess.Popen使用相对路径 [英] subprocess.Popen using relative paths

查看:1124
本文介绍了subprocess.Popen使用相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Popen的文档提到您可以' t指定相对于更改工作目录" kwarg的可执行路径.

The docs for Popen mention that you can't specify your executable path relative to the 'change working directory' kwarg.

如果cwd不为None,则孩子的当前目录将更改为 cwd在执行之前. 请注意,该目录不是 搜索可执行文件时考虑的因素,因此您无法指定 程序相对于cwd的路径.

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在我的系统上的行为似乎与这种说法直接矛盾:

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

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的相对路径依赖于平台且不应依赖?还是这是一个文档错误?

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

(此问题来自glglgl 此处的评论)

(this question spawns from a comment by glglgl here)

推荐答案

是的,这取决于平台.

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

On POSIX systems, the process is forked and in the child process a os.chdir(cwd) is executed before executing the executable.

但是,在Windows上, CreateProcess() API调用,并且cwd作为lpCurrentDirectory参数传入.没有目录更改发生,并且CreateProcess()调用在寻找要执行的lpApplicationName时不会查阅该参数.

On Windows however, the CreateProcess() API call is used and cwd is passed in as the lpCurrentDirectory parameter. No directory change takes place, and the CreateProcess() call does not consult that parameter when looking for the lpApplicationName to execute.

要保持应用程序跨平台,在查找可执行文件时,您不应依赖于当前工作目录进行更改.

To keep your application cross-platform, you should not rely on the current working directory to be changed when looking up the executable.

这篇关于subprocess.Popen使用相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆