【发布时间】:2025-12-28 16:10:06
【问题描述】:
如果shell 设置为true,ls 命令会给我一个不同的stdout。这是为什么呢?
是否有一个基本概念允许程序(在这种情况下为ls)检测它是否通过 shell 启动?
我注意到p1 和p2在 Windows 上共享相同的 stdout,但在 Linux 上却没有。
import subprocess
cmd = ['ls', '-la']
# Using shell
p1 = subprocess.run(executable=cmd[0], args=cmd[1:], shell=True, text=True, capture_output=True)
# Without using shell
p2 = subprocess.run(executable=cmd[0], args=cmd[1:], shell=False, text=True, capture_output=True)
print(p1.stdout)
print(p2.stdout)
Linux 上的输出
total 12
drwxr-xr-x 2 root root 4096 Feb 20 18:25 .
drwx------ 10 root root 4096 Feb 20 18:51 ..
-rw-r--r-- 1 root root 269 Feb 20 18:57 test.py
test.py
【问题讨论】:
-
当
args是一个列表时,我认为shell=True没有意义。 shell 将命令行作为单个字符串处理。 -
@Barmar 我通过将 args 作为字符串发送来检查,行为仍然取决于
ls是否作为 shell 运行。 -
我不确定到底发生了什么,但尝试更改为
cmd=['echo', 'foo', 'bar'],您会看到一些有趣的结果。当您使用shell=True时,executable用作外壳。
标签: python python-3.x shell subprocess