Running Bash Commands in Python

Execute Bash commands Python way

Possible duplicate of this question.

It is recommended to use subprocess module instead. os.system has been depreciated in favour of subprocess. For more information see subprocess documentation.

import subprocess

command = 'sudo add-apt-repository ppa:ondrej/php'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()

how to run bash inside python loop

You can use subprocess.run() or subprocess.check_output()
depending whether you need to simply run the script, or if you want the output to be returned in Python.

Here a silly example

bash_example.sh is

echo 'Hello from Bash'

From within python:

from subprocess import check_output

check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'

Run bash command in a python loop

One way to solve this is to get the current folder before the loop starts and you call chdir() for the first time. Then you can chdir() back to that folder.

How to run bash commands from Python preferably with the os library?

source is a bash built-in command, not an executable.

Use the full path to the python interpreter in your commands instead of venv activation, e.g. os.system('<venv>/bin/python ...').

The second option is to write your commands into a separate bash script and call it from python:

os.system('bash script.sh')


Related Topics



Leave a reply



Submit