简体   繁体   English

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

[英]Why I am getting an empty string?

I want to put the output of the bash command in a variable but I get an empty string. 我想将bash命令的输出放在一个变量中,但是得到一个空字符串。

import subprocess

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

the output is: 输出为:

hello world
 ok

instead of: 代替:

hello world
hello world ok

why does this happen? 为什么会这样?

The output of echo includes a newline. echo的输出包括换行符。 The result is not written to your terminal, the output is captured by check_output() , but you then print that output including the newline: 结果没有写入终端, check_output()捕获了输出,但是您随后输出包括换行符的输出:

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

giving you 'hello world' and ' ok' on two separate lines when printed. 在打印时在两行中分别为您提供'hello world'' ok'

You could remove the newline afterwards; 您可以随后删除换行符; using str.strip() would remove all whitespace from the start and end of the string, for example: 使用str.strip()会删除字符串开头和结尾的所有空格,例如:

print out.strip() + ' ok'

On some shells, the echo command takes an -n switch to suppress the newline: 在某些shell上, echo命令使用-n开关来禁止换行符:

echo -n hello world

One thing that comes to mind is that subprocess commands add a newline . 想到的一件事是子流程命令添加了换行符 It may be clumsy, but try this: 可能很笨拙,但是请尝试以下操作:

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

echo prints the text with a new line character \\n appended to it. echo打印带有附加换行符\\n的文本。 If you want to omit that, use printf instead. 如果要忽略它,请改用printf

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

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

You captured the output by invoking check_output . 您通过调用check_output捕获了输出。 According to the docs https://docs.python.org/2/library/subprocess.html#subprocess.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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM