subprocess.Popen 使用相对路径

subprocess.Popen using relative paths(subprocess.Popen 使用相对路径)

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

问题描述

Popen 的 docs 提到你可以'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:

/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
'
>>> 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 使用相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:subprocess.Popen 使用相对路径

基础教程推荐