Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine pid of process started via os.system

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")
like image 724
Sebastian Werk Avatar asked Nov 26 '13 13:11

Sebastian Werk


People also ask

How do you find the PID of a process?

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.

How do I find the PID of a running process in Linux?

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.

What is process ID OS?

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.

What command shows you the process used as PID 1?

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.


1 Answers

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()
like image 106
falsetru Avatar answered Sep 27 '22 02:09

falsetru