简体   繁体   English

将实时输出保存到python文件中

[英]Saving live output to file in python

This is taking all day to try to figure out why it's not working. 这需要花整整一天的时间来弄清楚为什么它不起作用。 This is with Python 3.6. 这是Python 3.6。

The goal is to capture the progress from a command line, shred as an example. 目标是从命令行捕获进度,以示例为例。 Shred would output line by line of the progress. 切细将逐行输出进度。

With Python subprocess, it cannot seem to save any output to the file. 使用Python子进程时,似乎无法将任何输出保存到文件中。 I did this: 我这样做:

   cmd_str="sudo shred -v /dev/sde"
   f="/test.log"

   with Popen(cmd_str, stdout=f, bufsize=1, universal_newlines=True) as p:
       for line in p.stdout:
           print(line, end='') 

But it generated an error saying: FileNotFoundError: [Errno 2] No such file or directory: 'sudo shred -v /dev/sde': 'sudo shred -v /dev/sde' which makes no sense to me. 但是它生成了一个错误消息:FileNotFoundError:[Errno 2]没有这样的文件或目录:'sudo shred -v / dev / sde':'sudo shred -v / dev / sde'对我来说毫无意义。

Simply put, I want a new line of output to be appended to the file and close it. 简而言之,我希望将新的输出行附加到文件并关闭它。 So that way, the external program can check the log file to see how the progress is going. 这样,外部程序可以检查日志文件以查看进度。

I just observed that when I use tee to see if it's logging and it's not logging to the file either despite creating the log file. 我只是观察到,当我使用tee来查看它是否正在记录日志时,即使创建了日志文件,它也未记录到文件中。

UPDATE: I have tried every possible solution in this site and nothing worked. 更新:我已经尝试了该站点中所有可能的解决方案,但没有任何效果。 I am starting to think if it has to do with the fact that it's a progress bar that is not capable of being sent to stdout? 我开始考虑是否与进度条无法发送到stdout有关? These are tried and yet failed to work: 这些已尝试但仍无法正常工作:

live output from subprocess command 子流程命令的实时输出

Constantly print Subprocess output while process is running 进程运行时不断打印子进程输出

Splitting your tokens is definitely recommended, and you'll probably need to use shell=True to get sudo to take: 绝对建议拆分令牌,您可能需要使用shell=True来获取sudo

   cmd_str="sudo shred -v /dev/sde"
   f="/test.log"

   with Popen(cmd_str.split(), shell=True, stdout=open(f, 'w'), bufsize=1, universal_newlines=True) as p:
       for line in p.stdout:
           print(line, end='')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM