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

标签 python python-3.x linux shell subprocess

我正在寻找一种在 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/

相关文章:

python - 交叉多个 2D np 数组以确定区域

python - 在 Pandas 数据框中替换大于 1 的值

python - 来自opencv矩形的奇怪错误

python - 在Python中使用concurrent.futures.ProcessPoolExecutor时为每个进程创建一个单独的记录器

java - 在linux CL中使用扩展ascii字符作为参数的问题

python - 数据帧循环中的 if/else 语句

python - 将 np.zeros 与 OpenCV 结合使用时,图像看起来曝光过度(几乎全白) imshow

python - 抓取电子邮件地址时无法删除不需要的东西

linux - 需要帮助修剪文件名文本

linux - 从 centos 中提取图像(最新)时出错,需要身份验证