[英]Python to execute shell and prints the stdout
printing stdout [1]僅打印單個字符。 如何打印單行而不是單個字符?
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])
取決於您的check.sh
外觀。 但是,如果這很簡單,請說:
#check.sh
echo "foo"
echo "bar"
然后,您可以decode()
(從字節到字符串)並在換行符( \\n
)上分割:
stdout.decode().split("\n")[0] # foo
在大輸出或流輸出時可能更快的另一種方法是考慮使用itertools
from itertools import takewhile
print("".join(takewhile(lambda x: x != "\n", stdout)))
這將繼續將字符輸入到join函數中,直到找到換行符或輸出結尾為止。
值得注意的是,此解決方案的特定實現僅適用於輸出的第一行-因此請進行相應調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.