如何将脚本的终端日志捕获到文件中?
How to capture the terminal log of script to a file?
我有一个 python
脚本,它 运行 从 Linux 终端成功运行。当我 运行 我的 python
脚本时,我可以使用 shell script
将终端输出收集到一个文件中。
现在我想从 python script
本身收集终端输出。但是做不到。
I want to do this using python
only not using any shell
or unix
scripting
我在 python file
中做了如下操作:
class Tee(object):
def __init__(self, f1, f2):
self.f1, self.f2 = f1, f2
def write(self, msg):
self.f1.write(msg)
self.f2.write(msg)
outfile = open('outfile', 'w')
sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)
python file
中的这部分代码将 stderr
和 stdout
都打印到输出文件。
如何将整个终端输出捕获到一个文件中。
如果您同意 PATH
中包含 python
的要求,那么我会调用另一个 python 进程来 运行 您的主脚本。
在您的顶级脚本中,使用 subprocess.Popen
在子进程中启动您想要的脚本。然后使用 subprocess.Popen.communicate()
从进程中获取输出流(并可能将任何命令行参数传递到进程中)。
您甚至可以使用 Popen 将所有 std* 输出重定向到文件,但这实际上取决于您的需要等等。 communicate()
似乎对您可能想做的事情很有用。
您可以在代码中使用类似这样的东西:os.system('pdv -t %s > 123.txt' % epoch_name)
你也可以看看这个:Subprocess
我有一个 python
脚本,它 运行 从 Linux 终端成功运行。当我 运行 我的 python
脚本时,我可以使用 shell script
将终端输出收集到一个文件中。
现在我想从 python script
本身收集终端输出。但是做不到。
I want to do this using
python
only not using anyshell
orunix
scripting
我在 python file
中做了如下操作:
class Tee(object):
def __init__(self, f1, f2):
self.f1, self.f2 = f1, f2
def write(self, msg):
self.f1.write(msg)
self.f2.write(msg)
outfile = open('outfile', 'w')
sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)
python file
中的这部分代码将 stderr
和 stdout
都打印到输出文件。
如何将整个终端输出捕获到一个文件中。
如果您同意 PATH
中包含 python
的要求,那么我会调用另一个 python 进程来 运行 您的主脚本。
在您的顶级脚本中,使用 subprocess.Popen
在子进程中启动您想要的脚本。然后使用 subprocess.Popen.communicate()
从进程中获取输出流(并可能将任何命令行参数传递到进程中)。
您甚至可以使用 Popen 将所有 std* 输出重定向到文件,但这实际上取决于您的需要等等。 communicate()
似乎对您可能想做的事情很有用。
您可以在代码中使用类似这样的东西:os.system('pdv -t %s > 123.txt' % epoch_name)
你也可以看看这个:Subprocess