Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PID by process name?

Is there any way I can get the PID by process name in Python?

  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND                                                                                          3110 meysam    20   0  971m 286m  63m S  14.0  7.9  14:24.50 chrome  

For example I need to get 3110 by chrome.

like image 676
B Faley Avatar asked Nov 01 '14 11:11

B Faley


People also ask

How do I find the PID of a process?

How to get PID using Task Manager. Press Ctrl+Shift+Esc on the keyboard. Go to the Processes tab. Right-click the header of the table and select PID in the context menu.

How do I find the PID of a process in Unix?

A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system. 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.


1 Answers

You can get the pid of processes by name using pidof through subprocess.check_output:

from subprocess import check_output def get_pid(name):     return check_output(["pidof",name])   In [5]: get_pid("java") Out[5]: '23366\n' 

check_output(["pidof",name]) will run the command as "pidof process_name", If the return code was non-zero it raises a CalledProcessError.

To handle multiple entries and cast to ints:

from subprocess import check_output def get_pid(name):     return map(int,check_output(["pidof",name]).split()) 

In [21]: get_pid("chrome")

Out[21]:  [27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997] 

Or pas the -s flag to get a single pid:

def get_pid(name):     return int(check_output(["pidof","-s",name]))  In [25]: get_pid("chrome") Out[25]: 27698 
like image 63
Padraic Cunningham Avatar answered Sep 28 '22 19:09

Padraic Cunningham