Running Bash Script from Within Python

Running bash script from within python

Making sleep.sh executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "sleep.sh" to "./sleep.sh".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0
>>>

Where test.sh is a simple shell script and 0 is its return value for this run.

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'

Shell Script: Execute a python program from within a shell script

Just make sure the python executable is in your PATH environment variable then add in your script

python path/to/the/python_script.py

Details:

  • In the file job.sh, put this
#!/bin/sh
python python_script.py
  • Execute this command to make the script runnable for you : chmod u+x job.sh
  • Run it : ./job.sh


Related Topics



Leave a reply



Submit