运行execfile()时向日志文件发送print()命令(Python)

运行execfile()时向日志文件发送print()命令(Python),python,Python,我有一个运行单独线程的程序,其中包含三个运行外部Python脚本的execfile()语句。在不更改这些脚本的情况下,是否有办法让其中的print()语句将其命令打印到日志文件中?从下面的代码中,我需要File1、File2和File3中的print命令进入日志文件,而不能更改这些文件。这可能吗 代码: MyThread.py import threading class MyThread(threading.Thread): def run(self): execfi

我有一个运行单独线程的程序,其中包含三个运行外部Python脚本的execfile()语句。在不更改这些脚本的情况下,是否有办法让其中的print()语句将其命令打印到日志文件中?从下面的代码中,我需要File1、File2和File3中的print命令进入日志文件,而不能更改这些文件。这可能吗

代码:

MyThread.py

import threading

class MyThread(threading.Thread):
    def run(self):
        execfile('File1.py')
        execfile('File2.py')
        execfile('File3.py')
Program.py

from MyThread import *

MyThread().start()
我在这里看到了Q/A()并尝试了此解决方案,但是外部文件中的print()语句没有添加到日志文件中:

import threading, sys

class MyThread(threading.Thread):
    def run(self):
        old_stdout = sys.stdout
        output_file = open('output.log', 'w')
        sys.stdout = output_file

        execfile('File1.py')
        execfile('File2.py')
        execfile('File3.py')

        sys.stdout = old_stdout
        output_file.close()

好的,所以这…很有趣。我所做的是使用print->file方法frm并将其添加到要运行的文件之前

my_thread.py

import threading

def prepend_stdout(filename):
        with open(filename, 'r+') as f:
            std_out = 'import sys\nold_stdout = sys.stdout\nlog_file = open("message.log","w")\nsys.stdout = log_file\n'
            content = f.read()
            return std_out + content


class MyThread(threading.Thread):
    def run(self):
        content = prepend_stdout("test.py")
        exec(content)


MyThread().start()
test.py

print("whatever, man")
然后我运行了
python my_-thread.py
,“message.log”中的输出是


我尝试了发布我的Cory Madden的解决方案,它一直工作到
exec()
调用(之后没有打印任何内容,从线程本身的
print()
调用)。然后我回到最初给出的建议答案()并做了一些不同的事情,解决了这个问题。通过在每个
execfile()
语句之后添加行
output\u file.flush()
,来自
execfile()
脚本的
print()
命令现在打印到外部日志文件。因此:

...
def run(self):
    old_stdout = sys.stdout
    output_file = open('path/to/file.log', 'w')
    sys.stdout = output_file

    execfile('File1.py')
    output_file.flush()
    execfile('File2.py')
    output_file.flush()
    execfile('File3.py')
    output_file.flush()

    output_file.close()
    sys.stdout = old_stdout

现在适用于我的实例。

可能重复的
~$./Program.py>output.log
?@willusdaman但如何在Program.py文件中而不是在命令行中执行此操作?@CodersinSpace提供您尝试按照我链接的示例执行的代码。我已经测试过了,效果很好。我甚至只是在
线程上测试了它。你为什么要这样做?为什么不编写一个打印到stdout并将其记录到文件中的函数呢?或者直接写入日志文件并跳过使用
print
函数。这对我来说几乎奏效,但在调用
exec()
文件后(或之前)也没有打印任何内容。事实上,我找到了一个迄今为止运行良好的更简单的解决方案。@CodersinSpace很高兴您能找到它。我想知道为什么我的版本不适合你。我承认这有点奇怪,但它确实对我有用。
...
def run(self):
    old_stdout = sys.stdout
    output_file = open('path/to/file.log', 'w')
    sys.stdout = output_file

    execfile('File1.py')
    output_file.flush()
    execfile('File2.py')
    output_file.flush()
    execfile('File3.py')
    output_file.flush()

    output_file.close()
    sys.stdout = old_stdout