Application Scenarios
In the Linux operations environment, we often encounter the maintenance of multiple programs on the same server, involving program startup, shutdown and restart operations.
Typically, there is an interdependent relationship between these programs that requires a sequential start-down operation.
Here are a few ways to get the process PID through the process name:
Method One:
Execute pidof command using Subprocess's Check_output function
from Import Check_output def get_pid (name): return Map (int,check_output (["pidof", Name]). Split ())
Method 2:
With the Pgrep command, Pgrep gets a slightly different result from pidof, with a few more process IDs for pgrep. The pgrep command can be executed using Subprocess's Check_output function.
Import subprocess def get_process_id (name): = subprocess. Popen (['pgrep'-f', name],stdout=subprocess. PIPE, shell=False) = child.communicate () [0] return for in Response.split ()]
Method 3:
Directly read the file in the/proc directory, this method does not need to start a shell, just read the/proc directory of the file interface to obtain the process information.
#!/usr/bin/env python ImportOSImportSYS forDirNameinchOs.listdir ('/proc'): ifDirName = ='Curproc': Continue Try: With open ('/proc/{}/cmdline'. Format (dirname), mode='RB') as Fd:content= Fd.read (). Decode (). Split ('\x00') exceptException:Continue forIinchSys.argv[1:]: ifIinchContent[0]:Print('{0:<12}: {1}'. Format (DirName,' '. Join (content))
Method 4:
Gets the current script's process PID
Import os os.getpid ()
Python uses the standard library to get the process PID based on the process name