为什么我得到一个空字符串?

时间:2015-02-08 12:57:57

标签: python subprocess

我想将bash命令的输出放在一个变量中,但我得到一个空字符串。

import subprocess

out = subprocess.check_output("echo hello world", shell=True)
print out + ' ok'

输出是:

hello world
 ok

而不是:

hello world
hello world ok

为什么会这样?

4 个答案:

答案 0 :(得分:3)

echo的输出包含换行符。结果 not 写入终端,输出由check_output()捕获,但您打印输出包括换行符:

>>> import subprocess
>>> out = subprocess.check_output("echo hello world", shell=True)
>>> out
'hello world\n'

在打印时在两个单独的行上为您提供'hello world'' ok'

之后您可以删除换行符;使用str.strip()会从字符串的开头和结尾删除所有空格,例如:

print out.strip() + ' ok'

在某些shell上,echo命令使用-n开关来禁止换行:

echo -n hello world

答案 1 :(得分:2)

我想到的一件事是子进程命令添加换行符。这可能很笨拙,但试试这个:

print out.rstrip('\n') + ' ok'

答案 2 :(得分:2)

echo打印文本,并附加一个换行符号\n。如果您想省略它,请改用printf

>>> import subprocess
>>> out = subprocess.check_output("printf 'hello world'", shell=True)

>>> print out
>>> 'hello world'

答案 3 :(得分:1)

您通过调用check_output捕获了输出。根据文档https://docs.python.org/2/library/subprocess.html#subprocess.check_output

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
    Run command with arguments and return its output as a byte string.
相关问题