4

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?

2
  • subprocess.call is doing you the favor of escaping the sequence for you. Consider the situation where the output file name is given by the user, and the user gives you the file name "out.txt; rm -rf *". If subprocess.call just dumped that as-is into a shell, you'd have a disaster on your hands. The correct solution is outlined by Anton Savin below. But, for your information, you could force subprocess.call to not escape anything by passing it shell = True, though this is a security issue and considered poor practice. Commented Aug 26, 2014 at 2:47
  • Thanks @RyanHaining! Helped me understand what is going on! Commented Aug 26, 2014 at 17:57

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

use with/as for the log file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.