Python uses the standard library to get the process PID based on the process name

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.