为什么子进程中的简单回显不起作用 [英] Why does simple echo in subprocess not working

查看:20
本文介绍了为什么子进程中的简单回显不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to perform simple echo operation using subprocess:

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" 它仍然不打印任何内容.任何帮助表示赞赏.

But it prints nothing. Even if I change the command to echo "hello, world" it still prints nothing. Any help is appreciated.

推荐答案

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

On Unix shell=True implies that 2nd and following arguments are for the shell itself, use a string to pass a command to the 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),

来自子进程的文档:

在带有 shell=True 的 Unix 上,shell 默认为/bin/sh.如果 args 是string,字符串指定要通过shell执行的命令.这意味着字符串必须完全按照它的格式进行格式化在 shell 提示符下键入时.这包括,例如,引用或反斜杠转义带有空格的文件名.如果 args 是序列,第一项指定命令字符串,任何附加项将被视为 shell 的附加参数本身.也就是说,Popen 相当于:

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], ...])

这篇关于为什么子进程中的简单回显不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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