I want to start several subprocesses with a programm, i.e. a module foo.py
starts several instances of bar.py
.
Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.
Even though the whole setup is pretty “dirty”, is there a good pythonic way to obtain a process’ pid
, if the process is started via os.system
?
foo.py:
import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))
bar.py:
import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort.
The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.
In computing, the process identifier (a.k.a. process ID or PID) is a number used by most operating system kernels—such as those of Unix, macOS and Windows—to uniquely identify an active process.
1) Finding a process ID (PID) with pidof command The pidof command is used to find the process ID of the running program. It prints those IDs into the standard output.
os.system
return exit code. It does not provide pid of the child process.
Use subprocess
module.
import subprocess
import time
argument = '...'
proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
time.sleep(3) # <-- There's no time.wait, but time.sleep.
pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.
To terminate the process, you can use terminate
method or kill
. (No need to use external kill
program)
proc.terminate()
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