简体   繁体   English

Python执行shell并打印stdout

[英]Python to execute shell and prints the stdout

printing stdout[1] prints only single character. printing stdout [1]仅打印单个字符。 How to print single line instead of single character? 如何打印单行而不是单个字符?

pr = subprocess.Popen(args=['./check.sh'], bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

(stdout, stderr) = pr.communicate(input=None)

print(stdout[1])

Depends on how your check.sh looks. 取决于您的check.sh外观。 But if it's something simple, say: 但是,如果这很简单,请说:

#check.sh
echo "foo"
echo "bar"

Then you can decode() (from bytes to string) and split on newlines ( \\n ): 然后,您可以decode() (从字节到字符串)并在换行符( \\n )上分割:

stdout.decode().split("\n")[0] # foo

An alternative way that could be faster on large outputs, or when streaming output is to consider itertools 在大输出或流输出时可能更快的另一种方法是考虑使用itertools

from itertools import takewhile
print("".join(takewhile(lambda x: x != "\n", stdout)))

This will keep feeding characters into the join function until it finds a newline character, or the end of the output. 这将继续将字符输入到join函数中,直到找到换行符或输出结尾为止。

It's worth noting that this specific implementation of the solution will only work with the first line of the output - so adjust accordingly. 值得注意的是,此解决方案的特定实现仅适用于输出的第一行-因此请进行相应调整。

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

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