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 code snippet:

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

This code should run nn.shwith inputs 172.20.125.44and 10and save the result in a file log.txt. When I run this Python script, it only shows the launch results nn.shon the screen, and it does not save them in the fill log.txt. However, if I print

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

on the command line, it correctly saves all the data in a file log.txt. Any ideas on what went wrong?

+4
source share
1 answer

You cannot use >>a subprocess in calls, use the parameter instead stdout:

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

All Articles