1

This is taking all day to try to figure out why it's not working. This is with 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. 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.

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.

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? These are tried and yet failed to work:

live output from subprocess command

Constantly print Subprocess output while process is running

netrox
  • 5,224
  • 14
  • 46
  • 60

1 Answers1

0

Splitting your tokens is definitely recommended, and you'll probably need to use shell=True to get sudo to take:

   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='')
mattbornski
  • 11,895
  • 4
  • 31
  • 25
  • File "/usr/lib/python3.6/subprocess.py", line 1184, in _get_handles c2pwrite = stdout.fileno() AttributeError: 'str' object has no attribute 'fileno' – netrox Sep 26 '18 at 22:47
  • ah yes, you'll need to pass a file object instead of a file name. edited to open the file for writing. – mattbornski Sep 26 '18 at 23:03