简体   繁体   中英

redirecting popen output to file in python

I have seen lot of answers that stdout=file will redirect to a file. But I had a couple of queries.

  1. Why doesn't >file work.

     subprocess.Popen([SCRIPT, "R", ">", FILE, "2>", "/dev/null"]) 
  2. Is this fine

     with open(FILE,'w+') as f: subprocess.Popen([SCRIPT, stdout=f] f.close() 

In my case I am trying to run a script in an infinite loop(which does not stop) and there is some other processes monitoring its output.

Does the script keeps writing into it even after f is closed. If yes, how does it work?

Because subprocess doesn't allow use > to redirect neither output nor error message, from the document:

stdin , stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are PIPE , DEVNULL , an existing file descriptor (a positive integer), an existing file object, and None .

PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None , no redirection will occur; the child's file handles will be inherited from the parent.

Additionally, stderr can be STDOUT , which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.


And you should use the following code:

with open(FILE, 'w+') as f:
    subprocess.Popen([SCRIPT, 'R'],  stdout=f, stderr=subprocess.DEVNULL))

Because you're using with , so no need close the file.

I think you must try,

with open(FILE,'w+') as f:
    subprocess.Popen([SCRIPT, stdout=f, stderr=f])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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