简体   繁体   中英

Python subprocess.Popen.wait(Popen) not redirecting output to file

This is a simple code but it echo es the output instead of redirecting output to file:

from subprocess import Popen

Popen.wait(Popen(['echo', 'echo', 'hi', '>', 'test']))

This is the output:

echo hi > test

But it does not create a file called test in the current directory.

I also tried these:

Popen.wait(Popen(['echo', 'echo', 'hi', '> test']))
Popen.wait(Popen(['echo', 'echo', 'hi >', 'test']))
Popen.wait(Popen(['echo', 'hi', '> test']))
Popen.wait(Popen(['echo', 'hi >', 'test']))
Popen.wait(Popen(['echo', 'hi', '> test']))

How to do this in this code? I prefer using Popen.wait(Popen...) .

Python subprocess does not allow to use ">" to redirect as stated in this answer :

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.


You would need to create the file first, for instance:

with open("test", 'w+') as f:
  Popen.wait(Popen(['echo', ' hi'], stdout=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