Sometimes you need to get the PID of a process, but you can't use a third-party library.
Method for Linux platforms.
Method 1
Execute pidof command using Subprocess's Check_output function
From subprocess import check_outputdef get_pid (name): return Map (Int,check_output (["Pidof", Name]). Split ()) in [21 ]: Get_pid ("Chrome") out[21]: [27698, 27678, 27665, 27649, 27540, 27530,]
Method 2
With the Pgrep command, Pgrep gets a slightly different result than pidof. Pgrep has a slightly more process ID. pgrep command enables subprocess functions that apply Check_out
Import subprocess
def get_process_id (name): "" " Return Process IDs found by (partial) name or regex. >>> get_process_id (' Kthreadd ') [2] >>> get_process_id (' watchdog ') [10, 11, 16, 21, 26, *, YMMV >>> get_process_id (' non-existent process ') [] "" "" "Child = subprocess. Popen ([' Pgrep ', '-f ', name], stdout=subprocess. PIPE, shell=false) response = child.communicate () [0] return [INT (PID) for PID in Response.split ()]
Method 3
Directly read the files in the/proc directory. This method does not need to start a shell, only need to read the files in the/proc directory to obtain the process information.
#!/usr/bin/env pythonimport osimport sysfor dirname in Os.listdir ('/proc '): if DirName = = ' Curproc ': Continue Try:with open ('/proc/{}/cmdline '. Format (dirname), mode= ' RB ') as FD: Content = Fd.read (). Decode (). Split (' \x00 ') except exception:continue for I in Sys.argv[1:]: If I in Content[0]: print (' {0:<12}: {1} '. Format (dirname, ". Join (content))
phoemur ~/python $ ./pgrep.py bash1487 : -bash 1779 : /bin/bash
4, gets the current script of the PID process
Import Osos.getpid ()
Python gets the PID of the process using the standard library based on the process name