Python-实时获取shell输出并将所有输出存储在变量中

问题描述 投票:0回答:1

[我正在寻找一种简单的方法来在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
python python-3.x linux shell subprocess
1个回答
0
投票

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()

这将包括所有换行符。我希望这能解决您的问题。如果不能随时返回评论部分。

© www.soinside.com 2019 - 2024. All rights reserved.