gpt4 book ai didi

Python:在 Linux 上,subprocess.Popen() 与 shell = True 一起工作很奇怪

转载 作者:行者123 更新时间:2023-11-28 20:48:30 34 4
gpt4 key购买 nike

如果我在 Windows 上执行以下 python 代码:

import subprocess
subprocess.Popen( [ 'python', 'foo' ], shell = True ).communicate()

如预期的那样,我将错误写入标准输出:

python: can't open file 'foo': [Errno 2] No such file or directory

但是如果我在 linux(ubuntu,OSX - 任何)上执行相同的代码,我会启动交互式 python REPL 而不是这个文本!像这样:

user@debian:~/Documents$ python test.py
Python 2.7.3 (default, Jab 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information
>>>

为什么会有这种奇怪的行为?使用参数 ('foo') 执行 python 解释器必须在所有平台上将其置于评估模式,而不是进入 REPL 模式。

最佳答案

这在文档中有详细说明:

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

(强调我的)

关于Python:在 Linux 上,subprocess.Popen() 与 shell = True 一起工作很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840427/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com