Python subprocess


How do you call a script written in another language in Python?

You can use the subprocess module.

Run

Let’s say you have the bash script hello_world.sh:

echo Hello, world!

In your Python script, use subprocess.run:

import subprocess

subprocess.run(["bash", "hello_world.sh"])

If subprocess.run isn’t available (Python <3.5), use subprocess.call instead:

subprocess.call(["bash", "hello_world.sh"])

When you run your Python script in your command-line:

python main.py # Hello, world!

Output

To get the output of the script, use subprocess.Popen to get the process:

import subprocess

proc = subprocess.Popen("bash hello_world.sh", shell=True, stdout=subprocess.PIPE)

Then read stdout with Popen.communicate:

outs, errs = proc.communicate()

Alternatively, you can use stdout.read:

outs = proc.stdout.read()

Decode the binary and print the string:

print(outs.decode("ascii"))

Demo

Repl.it:



Please support this site and join our Discord!