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
How to Convert Webpage into Pdf by Using Python
How to Iterate Over a List in Chunks
Replacements For Switch Statement in Python
What Exactly Do "U" and "R" String Prefixes Do, and What Are Raw String Literals
What Is the Purpose of the Single Underscore "_" Variable in Python
Of the Many Findelement(S)/By Functions in Selenium, When Would You Use One Over the Other
Are Global Variables Thread-Safe in Flask? How to Share Data Between Requests
Selenium "Selenium.Common.Exceptions.Nosuchelementexception" When Using Chrome
How to Import a Module Given the Full Path
How to List All Files of a Directory
How to Add to the Pythonpath in Windows, So It Finds My Modules/Packages