0

Very new to Python.

I have a Python script with a menu. At one selection, I want to start or call another script but it's BASH. The result is put in a text file in /tmp. I want to do this: Start Python script. At menu selection, have it start the BASH script. At end return back to Python script which processes the file in /tmp. Is this possible? How would I do it?

donde
  • 17
  • 4
  • http://stackoverflow.com/questions/3777301/how-to-call-a-shell-script-from-python-code – sudo bangbang Apr 24 '16 at 18:30
  • 1
    Duplicate of plenty of questions http://stackoverflow.com/questions/4256107/running-bash-commands-in-python http://stackoverflow.com/questions/26236126/how-to-run-bash-command-inside-python-script http://stackoverflow.com/questions/89228/calling-an-external-command-in-python – Joseph Farah Apr 24 '16 at 18:32

1 Answers1

3

You're looking for the subprocess module, which is part the standard library.

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

In Unix systems, this means subprocess can spawn new Unix processes, execute their results, and fetch you back their output. Since a bash script is executed as a Unix process, you can quite simply tell the system to run the bash script directly.

A simple example:

import subprocess
ls_output = subprocess.check_output(['ls']) # returns result of `ls`

You can easily run a bash script by stringing arguments together. Here is a nice example of how to use subprocess.

All tasks in subprocess make use of subprocess.Popen() command, so it's worth understanding how that works. The Python docs offer this example of calling a bash script:

>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Note the only important part is passing a list of arguments to Popen().

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44