3

I'm using Python to call bash to execute another bash script:

begin = int(sys.argv[1])
result = os.system("/tesladata/isetools/cdISE.bash %s" %begin)

After I printed result, it not only gives me the output but also the return status (0 here). What should I do if I only need the output?

And also, just for curiosity, how many ways are there to call bash in Python? I'll be glad if somebody can give me some references of how to use them, I've found only os.system() and os.popen() so far.

Smern
  • 18,746
  • 21
  • 72
  • 90
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Your second question was discussed here (http://stackoverflow.com/questions/3479728/is-it-good-style-to-call-bash-commands-within-a-python-script-using-os-systemb) and (http://stackoverflow.com/questions/4256107/running-bash-commands-in-python) Here – Bry6n Jan 11 '12 at 16:49

4 Answers4

7

Actually, result is only the return status as an integer. The thing you're calling writes to stdout, which it inherits from your program, so you're seeing it printed out immediately. It's never available to your program.

Check out the subprocess module docs for more info:

http://docs.python.org/library/subprocess.html

Including capturing output, and invoking shells in different ways.

AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • 4
    Specifically, it looks like he wants [subprocess.check_output](http://docs.python.org/library/subprocess.html#subprocess.check_output) – Thomas K Jan 11 '12 at 17:05
6

You can just throw away any output by piping to /dev/null.

begin = int(sys.argv[1])
result = os.system("/tesladata/isetools/cdISE.bash %s > /dev/null" %begin)

If you don't want to display errors either, change the > to 2&> to discard stderr as well.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
2

you can use the subprocess module like this assign it to a var (x for ex)

import subprocess
x = subprocess.run('your_command',capture_output=True)
2

Your python script does not have the output of the bash script at all, but only the "0" returned by it. The output of the bash script went to the same output stream as the python script, and printed before you printed the value of result. If you don't want to see the 0, do not print result.

William Pursell
  • 204,365
  • 48
  • 270
  • 300