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

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

问题描述

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

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本身,请使用字符串将命令传递给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是一个 字符串,该字符串指定要通过外壳执行的命令. 这意味着该字符串必须完全按照其格式进行格式化 在shell提示符下键入时.例如,这包括引号或 反斜杠转义使用空格的文件名. 如果args是一个 顺序,第一项指定命令字符串,以及任何 其他项目将被视为外壳程序的其他参数 本身.也就是说,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天全站免登陆