I have a python script which takes an input, formats it into a command which calls another script on the server, and then executes using subprocess:
import sys, subprocess
thingy = sys.argv[1]
command = 'usr/local/bin/otherscript.pl {0} &'.format(thingy)
command_list = command.split()
subprocess.call(command_list)
I append &
to the end because otherscript.pl
takes some time to execute, and I prefer to have run in the background. However, the script still seems to execute without giving me back control to the shell, and I have to wait until execution finishes to get back to my prompt. Is there another way to use subprocess
to fully run the script in background?
Placing a Running Foreground Process into the BackgroundExecute the command to run your process. Press CTRL+Z to put the process into sleep. Run the bg command to wake the process and run it in the backround.
Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.
2: Using CTRL + Z, bg command. You can then use the bg command to push it to the background. While the process is running, press CTRL + Z. This returns your shell prompt. Finally, enter the bg command to push the process in the background.
&
is a shell feature. If you want it to work with subprocess
, you must specify shell=True
like:
subprocess.call(command, shell=True)
This will allow you to run command in background.
Notes:
Since shell=True
, the above uses command
, not command_list
.
Using shell=True
enables all of the shell's features. Don't do this unless command
including thingy
comes from sources that you trust.
This alternative still lets you run the command in background but is safe because it uses the default shell=False
:
p = subprocess.Popen(command_list)
After this statement is executed, the command will run in background. If you want to be sure that it has completed, run p.wait()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With