简体   繁体   中英

Python subprocess.call function does not redirect output

I am trying to run a shell script called nn.sh (which constantly runs a Linux command over time), from within a python file. I am using the following piece of code:

from subprocess import call, Popen, PIPE
call(['/bin/sh', 'nn.sh', '172.20.125.44', '10', '>>', 'log.txt'])

This code is supposed to run nn.sh with inputs 172.20.125.44 and 10 and stores the result in the file log.txt . When I run this Python script, it only shows the results of running nn.sh on the screen and it does not save them in the fill log.txt . However, if I type

/bin/sh nn.sh 172.20.125.44 10 >> log.txt

in the command line, it is correctly saving all the data into the file log.txt . Any ideas on what goes wrong?

You can't use >> in subprocess calls, instead use stdout parameter:

with open("log.txt", "at") as log:
    call(['/bin/sh', 'nn.sh', '172.20.125.44', '10'], stdout = log)

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