簡體   English   中英

在從控制台存儲實時輸出時如何運行python腳本?

[英]How to run a python script while storing live output from the console?

我想創建一個執行python腳本的函數,同時在執行過程中實時存儲控制台輸出。

例如,我使用子進程模塊運行example.py,但是我只在整個腳本運行后才收到控制台輸出,而不是在發生控制台輸出時獲得控制台輸出。 換句話說,按照下面的腳本,我想立即接收控制台輸出“ hello world”,然后等待60秒,然后接收控制台輸出“再見世界”

example.py

import time 

print "hello world!"
time.sleep(60)
print "goodbye world"

以下是在example.py中運行腳本並在之后存儲控制台的腳本

import subprocess
script = open('example.py',"r+").read()
process = subprocess.Popen(['python', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.stdin.write(script)
stored_console_output, stored_console_output_error = process.communicate()
print stored_console_output

整個腳本執行完畢后,將以下內容作為字符串返回

hello world!
goodbye world

注意:我無法更改python腳本example.py。 我只能更改調用它的函數。

除了使控制台輸出實時(如果可能)之外,我還想獲得導致該控制台輸出的python行。 例如,我想達到以下目標

import time 

print "hello world!"
hello world
time.sleep(60)
print "goodbye world"
goodbye world

我也嘗試利用sys模塊,但它不存儲控制台輸出:

import sys
import inspect

class SetTrace(object):
    def __init__(self, func):
        self.func = func

    def __enter__(self):
        sys.settrace(self.func)
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        sys.settrace(None)

def monitor(frame, event, arg):
    if event == "line":
        print event
    return monitor


with SetTrace(monitor):
    exec(open('example.py',"r+").read())

這將返回以下內容並成功運行。

line
line
line
hello world!
line
line
goodbye world
line

這篇文章很大程度上回答了您的問題,盡管特別是有一條評論提供了您特定問題的關鍵:調用example.py時需要-u標志,以防止STDOUT緩沖在sleep()

從上述答案中大量借用,此解決方案有效:

from subprocess import Popen, PIPE

def execute(cmd):
    popen = Popen(cmd, stdout=PIPE, universal_newlines=True)
    for stdout_line in iter(popen.stdout.readline, ""):
        yield stdout_line 
    popen.stdout.close()

for statement in execute(['python', '-u', 'example.py']):
    print(statement, end="")

輸出:

Hello
# pauses for the number of sleep seconds
Goodbye

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM