简体   繁体   English

解析 Python subprocess.check_output()

[英]Parsing Python subprocess.check_output()

I am trying to use and manipulate output from subprocess.check_output() in python but since it is returned byte-by-byte我正在尝试使用和操作 python 中的 subprocess.check_output() 中的 output 但因为它是逐字节返回的

for line in output:
    # Do stuff

Does not work.不起作用。 Is there a way that I can reconstruct the output to the line formatting that it has when it is printed to stdout?有没有一种方法可以将 output 重建为打印到标准输出时的行格式? Or what is the best way to search through and use this output?或者搜索和使用这个 output 的最佳方式是什么?

Thanks in advance!提前致谢!

subprocess.check_output() returns a single string . subprocess.check_output()返回单个字符串 Use the str.splitlines() method to iterate over individual lines in that string: 使用str.splitlines()方法迭代该字符串中的各个行:

for line in output.splitlines():

For anyone following along:对于任何跟随的人:

output = subprocess.check_output(cmd, shell=True)

for line in output.splitlines():
   print(line)

will output:将 output:

b'first line'
b'second line'
b'third line'

doing:正在做:

output = subprocess.check_output(cmd, shell=True)

output = output.decode("utf-8")
for line in output.splitlines():
   print(line)

will output:将 output:

first line
second line
third line

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

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