I have seen lot of answers that stdout=file
will redirect to a file. But I had a couple of queries.
Why doesn't >file
work.
subprocess.Popen([SCRIPT, "R", ">", FILE, "2>", "/dev/null"])
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
andstderr
specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values arePIPE
,DEVNULL
, an existing file descriptor (a positive integer), an existing file object, andNone
.
PIPE
indicates that a new pipe to the child should be created.DEVNULL
indicates that the special fileos.devnull
will be used. With the default settings ofNone
, no redirection will occur; the child's file handles will be inherited from the parent.Additionally,
stderr
can beSTDOUT
, which indicates that the stderr data from the applications should be captured into the same file handle as forstdout.
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.