Printing an python script output to BOTH a text file and command window
因此,我知道如何执行python脚本并使用os.command甚至子进程将其输出到命令窗口中。我也知道捕获输出到文本文件是通过os.command('my command> me.txt"完成的。
我的问题是:
有没有办法用一个命令同时做这两个事情?即执行python脚本,将输出捕获到文本文件,并在命令窗口中显示?
如果这不可能,这是另一个问题:
我要执行的命令最多需要8分钟才能完成,并在一个文本文件中最多写入300行。我可以在命令仍在执行时访问文本文件以获取一些数据,而不必等待命令完成执行吗?例如每1分钟访问一次文本文件?
如果两者都不可行,那么也可以完成此工作:
当我的命令成功执行时,它会在cmd以及许多其他行上打印出一条Done语句。我可以在cmd中检查是否已打印"完成"字符串,或者是否需要在文本文件中捕获该字符串才能进行破坏活动?
在将命令输出回显至标准输出时,保存命令输出的最简单方法是使用
1 | $ python script.py | tee logfile.log |
如果要在写入文件时跟踪文件的输出,请使用
1 | $ tail -f logfile |
您可能希望立即
1 2 | $ unbuffer python script.py > logfile $ tail -f logfile |
要么
1 | print ("to file..", flush = True) |
我设计的更简单的方法是创建一个可以同时打印到屏幕和文件的功能。 当您输入输出文件名作为参数时,以下示例适用:
1 2 3 4 5 6 7 8 9 10 11 12 | OutputFile= args.Output_File if args.Output_File: OF = open(OutputFile, 'w') def printing(text): print text if args.Output_File: OF.write(text +" ") #To print a line_of_text both to screen and file all you need to do is: printing(line_of_text) |
如果您可以从脚本中而不是命令行中执行此操作,那将非常容易。
1 2 3 | with open("output.txt","w") as output: print>>output,"what you want as output" #prints to output file print"what you want as output" #prints to screen |