Running a Bash Script from 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.

run bash script in background with process name

You can run programs with a specific command name by using the bash buildin exec. Note that exec replaces the shell with the command so you have to run it in a subshell environment like:

( exec -a my_new_name my_old_command ) &

However, it probably won't help you much because this sets the command line name, which is apparently different from the command name. So executing the above snippet will show your process as "my_new_name" for example in top or htop, but pkill and killall are filtering by the command name and will thus not find a process called "my_new_name".

While it is interesting, how one can start a command with a different name than the executable, it is most likely not the cause of your problem. PIDs never change, so I assume that the problem lays somewhere different.

My best guess is that the server binds a socket to listen on a specific port. If the program is not shutdown gracefully but killed the port number remains occupied and is only freed by the kernel after some time during some kind of kernel garbage collect. If the program is restarted after a short period of time it finds the port already been occupied and prints a misleading message, that says it is already running. If that is indeed the cause of your problem I would strongly consider implementing a way to graceful shutdown the server. (may be already closing the socket in a destructor or something similar could help)

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'


Related Topics



Leave a reply



Submit