6

I'm relatively new to both Python and bash. However, I am finding Python much more intuitive and easier than bash. I have a few bash scripts I have managed to cobble together, but I would like to replace them with Python scripts - for ease of maintenance etc.

The bash scripts essentially run python scripts, check the returned status code and act appropriately (e.g. log a message, fire off an email etc) - this is functionality that I thing I can for the most part, reproduce in a Python script.

The one thing I am not sure of how to do, is how to run a python script from another python script and get the returned status code.

Can anyone post a snippet here that will show how to run a small python script 'test.py' from a main python script 'master.py' and correctly retrieve the return code after running test.py from master.py?

Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • 2
    You can always just import another python program (ie: having 'test.py' in the same directory as your running code, and calling: import test) to easily run secondary code, but it won't manage your return code business – Anti Earth Jan 04 '12 at 09:34

2 Answers2

6

Using subprocess module

master.py

import subprocess
retcode = subprocess.call(["/usr/bin/python", "/path/to/test.py"])
print "Return code of test.py is ", retcode
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
0

I would suggest you to look at the subprocess module in python. You can start another process using it, manipulate its streams and get the return code.

Divya
  • 2,594
  • 1
  • 17
  • 29