我正在寻找一种在 python 3 中运行 shell 命令、实时获取其输出并最终将所有输出存储到变量的简单方法。
我在网上搜索了一种可能的解决方案,但找不到。 我还在 this site 上发现了类似的问题,但没有人给出明确的答案。 我最终得到了这段代码,但它更像是一种解决方法,而不是一个明确的解决方案
def get_os_cmd(command):
proc_file = '/tmp/proc.tmp'
if os.path.isfile(proc_file):
os.remove(proc_file) # remove temporary file
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True, encoding='utf-8')
with open(proc_file, 'a+') as f:
for line in iter(proc.stdout.readline, ''):
string = line.rstrip()
print(string)
f.write(f'{string}\n')
return proc.stdout, proc.returncode
最佳答案
doki.al 这个程序很好,我认为会很好用。
import os
command = ['dir', 'echo program working']
for i in command:
stream = os.popen(i) # Execute the command in command list
output = stream.read() # Read the output of the executed program
print(output) # Print the output
本程序先执行cmd中的一条命令,然后读取并显示。
此程序将变量输出作为字符串返回。 如果你想要一个列表,你可以使用
output = stream.readline()
这将包括所有换行符。 我希望这能解决你的问题。如果不方便,请随时返回评论部分。
关于python - 实时获取 shell 输出并将所有输出存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58309881/