Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside python code, how do I run a .sh script?

Tags:

python

bash

shell

Will it continue the code after it's run? Or will it stop at that line until the script is done?

like image 481
TIMEX Avatar asked Jan 28 '11 09:01

TIMEX


People also ask

Can Python run shell script?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

Can you run a bash script from Python?

Is there any way to execute the bash commands and scripts in Python? Yeah, Python has a built-in module called subprocess which is used to execute the commands and scripts inside Python scripts.


3 Answers

Using subprocess.call is the easiest way. It will not return until the executed program has terminated. Have a look at the other methods of the subprocess module if you need different behaviour.

like image 79
ThiefMaster Avatar answered Oct 12 '22 22:10

ThiefMaster


import os
os.system('./script.sh')

python script won't stop until sh is finished

like image 43
Frost.baka Avatar answered Oct 12 '22 23:10

Frost.baka


You can use os.system or subprocess.Popen or subprocess.call but when using subprocess methods make sure you use shell=True. And executing it via system call in all these methods is blocking. The python script will complete and then go the next step.

like image 26
Senthil Kumaran Avatar answered Oct 12 '22 23:10

Senthil Kumaran