Python uses the standard library to explain how to obtain the process pid based on the process name, pythonpid

Source: Internet
Author: User

Python uses the standard library to explain how to obtain the process pid based on the process name, pythonpid

Preface

The standard library is an integral part of Python. These standard libraries are a powerful tool for Python, allowing programming to get twice the result with half the effort. In particular, it is sometimes necessary to obtain the pid of the process, but it cannot use a third-party library. I won't talk much about it below. Let's take a look at the detailed introduction.

This method is applicable to linux.

Method 1

Run the pidof command using the check_output function of subprocess.

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

Using the pgrep command, the results obtained by pgrep are slightly different from those obtained by pidof. The pgrep process IDs are slightly more. The pgrep command can be used to execute the check_out function applicable to subprocess.

import subprocess<br data-filtered="filtered">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, 31, 36, 41, 46, 51, 56, 61] # 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. You only need to read the files in the/proc directory to obtain the process information.

#!/usr/bin/env python import osimport sys  for 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)))<br data-filtered="filtered"><br data-filtered="filtered">
phoemur ~/python $ ./pgrep.py bash1487   : -bash 1779   : /bin/bash

4. Obtain the pid process of the current script

import os os.getpid()

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.