gpt4 book ai didi

python - 为什么子进程中的简单回显不起作用

转载 作者:IT王子 更新时间:2023-10-29 00:18:48 26 4
gpt4 key购买 nike

我正在尝试使用子进程执行简单的回显操作:

import subprocess
import shlex

cmd = 'echo $HOME'
proc = subprocess.Popen(shlex.split(cmd), shell=True, stdout=subprocess.PIPE)
print proc.communicate()[0]

但它什么也不打印。即使我将命令更改为 echo "hello, world" 它仍然不打印任何内容。感谢您的帮助。

最佳答案

在 Unix 上 shell=True 意味着第二个和后面的参数是针对 shell 本身的,使用字符串将命令传递给 shell:

import subprocess

cmd = 'echo $HOME'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
print proc.communicate()[0],

你也可以这样写:

import subprocess

cmd = 'echo $HOME'
print subprocess.check_output(cmd, shell=True),

来自 the subprocess' docs :

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. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

关于python - 为什么子进程中的简单回显不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226912/

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