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?

2

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.