Python get process name by pid

How to determine a running process given its PID in python on Windows OS?

I have a python script that launches an application, and grabs the PID, and waits until that process ID is no longer found by using :

result = subprocess.Popen( r'tasklist /fi "PID eq ' + str(PID) + '"', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

This works fine for me, until I try to run it on XP Home which of course, doesn’t have tasklist.exe Is there another way of detecting if a process is running or not, given the PID of the process. Simply launching the process with subprocess.Popen and waiting for it to finish is NOT an option as the process must be detached as I need to perform other tasks while the initial process is running. Any thoughts?

you might want to use psutil library in python and use psutil.pid_exists(pid) to check if process is running or not.unless you have to only use Subprocess

Does XP Home have taskmgr.exe, and if so, why does it have that but not tasklist.exe? It seems to me there’s no reason to have the GUI version but not the CLI version. . Also, can you copy over the XP version of tasklist.exe from a non-Home XP machine? Would be interesting to see if it’d work.

2 Answers 2

If you don’t mind installing the Python Win32 extensions, you can use the Windows API to wait for the process to exit like so:

from win32con import SYNCHRONIZE from win32event import WaitForSingleObject, INFINITE from win32api import OpenProcess, CloseHandle process_handle = OpenProcess(SYNCHRONIZE, False, pid) try: WaitForSingleObject(process_handle, INFINITE) finally: CloseHandle(process_handle) 

This will cause the code to block until the process exits (the INFINITE in the WaitForSingleObject() value can be changed if desired; see the documentation).

Alternatively, without installing an extension, you can do this with ctypes , especially easy as all the necessary methods are in kernel32.dll :

from ctypes import windll SYNCHRONIZE = 0x100000L INFINITE = 0xFFFFFFFFL process_handle = windll.kernel32.OpenProcess(SYNCHRONIZE, 1, pid) windll.kernel32.WaitForSingleObject(process_handle, INFINITE) windll.kernel32.CloseHandle(process_handle) 

Of course, in this case, the error handling code (omitted) is a bit more complex and far less Pythonic.

Источник

Getting name of process from PID using python

My goal is to be able to access the name of a process that I know the process name and PID of. I’m not looking for the process name. That’s the general goal but to be clear I’ll use the specific example I’m working on. I want to be able to determine the current song being played on Spotify, but can’t use the API because I would want to determine it every couple of seconds and I’m not sure it would be a good idea to keep pinging the API (which is how I’m assuming it works). A solution I can see is that the main app process names itself after the current song in task manager (but it’s process name is still spotify.exe) as can be seen here My question is can I access that specific name, preferably with python? I’ve also checked powershell tasklist /svc and it isn’t used there as a service name. Thanks

Читайте также:  Php показывать ошибку 500

Searching for running processes and then accessing them in a way they weren’t meant to is a brittle endeavor. You should really use the API. Yes, they have a rate limit, but they also tell you when you hit the rate limit and when it’s fine to repeat your request. developer.spotify.com/documentation/web-api/#rate-limiting

@MikeMcCartin unfortunately the module doesn’t seem to be able to be able to access the «name» that appears in task manager, only the process name (which will always be Spotify.exe)

@blubberdiblub I think I misunderstand you, but I wouldn’t be searching for the process or it’s PID, just the one name that appears in task manager (knowing PID). I may use the API if I can’t access that name, or if the current playing song isn’t being held locally on the device.

Well, what I mean is when you do it the way you suggest you’re relying on OS behavior (how the OS presents the name to you, which can change with an OS update), on third party application behavior (how the Spotify application presents the song in the application name, which can change on Spotify update) and you still need to reliably retrieve the PID from some place so it still works after you restart Spotify or after you reboot. It’s really fine to do it like that for practice and for education purposes, but it’s unclean for a more serious application. The clean way is using the API.

Источник

How to get the process name by pid in linux using python?

In order to get the process name by pid in Linux using Python, there are a few different methods you can use. Here is an overview of three different methods, each with an example and a detailed explanation of how it works:

Method 1: Using the psutil library

  • Step 1 — Install the psutil library by running the command «pip install psutil» in your terminal.
  • Step 2 — Import the psutil library in your Python script by adding «import psutil» at the top of your script.
  • Step 3 — Use the psutil.Process() function, passing in the pid as an argument

This will create a Process object.

  • Step 4 — Call the .name() function on the Process object created in step 3, which will return the process name as a string.

Here is an example of how you would use this method:

import psutil pid = 1234 process = psutil.Process(pid) print(process.name())

In this example, the variable pid is set to 1234 and passed as an argument to the psutil.Process() function. This creates a Process object that represents the process with the pid of 1234. The .name() function is then called on this object, which returns the name of the process as a string.

Читайте также:  Functions in javascript with function as property

The psutil library is a third-party library that provides various system-related information like process, memory, and CPU usage. This library is built on top of the python built-in library called os, os.popen and subprocess and it also provides a cross-platform alternative for some of the os and subprocess functions.

Method 2: Using the os library

  • Step 1 — Import the os library in your Python script by adding «import os» at the top of your script.
  • Step 2 — Use the os.popen() function, passing in the command «ps -p [pid] -o comm=» as an argument

This will execute the command in the terminal and return the output as a file object.

  • Step 3 — Use the read() function on the file object returned in step 2 to read the output of the command as a string.
  • Step 4 — Use the strip() function on the string returned in step 3 to remove any leading or trailing whitespace.

Here is an example of how you would use this method:

import os pid = 1234 command = "ps -p " + str(pid) + " -o comm token operator">= os.popen(command).read().strip() print(process_name)

In this example, the variable pid is set to 1234 and the os.popen() function is used to execute the command «ps -p 1234 -o comm=» in the terminal. The output of this command is a string that contains the process name. The read() function is used to read the output as a string, and the strip() function is used to remove any leading or trailing whitespace.

The os library is a python built-in library which provides a way to interact with the underlying operating system. os.popen() function is used to open a pipe to or from command.

Method 3: Using the subprocess library

  • Step 1 — Import the subprocess library in your Python script by adding «import subprocess» at the top of your script.
  • Step 2 — Use the subprocess.run() function, passing in the command «ps -p [pid] -o comm=» as a

list of arguments and setting the stdout argument to subprocess.PIPE. This will execute the command in the terminal and return the output as a string.

  • Step 3 — Use the decode() function on the string returned in step 2 to convert it from bytes to a string.
  • Step 4 — Use the strip() function on the string returned in step 3 to remove any leading or trailing whitespace.

Here is an example of how you would use this method:

import subprocess pid = 1234 command = ["ps", "-p", str(pid), "-o", "comm token punctuation">] result = subprocess.run(command, stdout=subprocess.PIPE) process_name = result.stdout.decode().strip() print(process_name)

In this example, the variable pid is set to 1234 and the subprocess.run() function is used to execute the command [«ps», «-p», «1234», «-o», «comm=»] in the terminal. The output of this command is a bytes string that contains the process name. The stdout=subprocess.PIPE argument captures the output of the command as the result.stdout attribute. The decode() function is used to convert the output from bytes to a string and the strip() function is used to remove any leading or trailing whitespace.

Читайте также:  Код красивой формы html

The subprocess library is a python built-in library which provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. subprocess.run() function is a more high-level function for running a command and it returns a CompletedProcess instance. This method is a little bit more complex than the previous methods but it gives you more control over the process running.

Conclusion

In conclusion, getting the process name by pid in Linux using Python can be done by using the psutil library, the os library, or the subprocess library. Each of these methods has its own advantages and disadvantages, and the choice of which method to use will depend on the requirements of your specific project. The psutil library is the easiest and most convenient method, while the os and subprocess libraries provide more control over the process running. It is important to understand the basic concepts of the libraries and the command-line tools involved in the process, in order to effectively use any of these methods.

Источник

Get process name by PID

This should be simple, but I’m just not seeing it. If I have a process ID, how can I use that to grab info about the process such as the process name.

5 Answers 5

Under Linux, you can read proc filesystem. File /proc//cmdline contains the commandline.

An alternative is ps -o cmd= . And /proc//comm actually gives the process name.

Works fine on Windows and Unix, I recall.

I agree with you both, and it’s something I would have done if it were on a particular server, but it’s for an application that we’re distributing that still only supports debian 5 at this time 😉 . Reading /proc will just be easier and more reliable for us to manage in the long run.

I am using p.name() which is truncating the output. Is there any other way to get the complete process name??

A Way to get all the pids of programs on your computer without downloading any modules:

import os pids = [] a = os.popen("tasklist").readlines() for x in a: try: pids.append(int(x[29:34])) except: pass for each in pids: print(each) 

If you just wanted one program or all programs with the same name and you wanted to kill the process or something:

import os, sys, win32api tasklistrl = os.popen("tasklist").readlines() tasklistr = os.popen("tasklist").read() print(tasklistr) def kill(process): process_exists_forsure = False gotpid = False for examine in tasklistrl: if process == examine[0:len(process)]: process_exists_forsure = True if process_exists_forsure: print("That process exists.") else: print("That process does not exist.") raw_input() sys.exit() for getpid in tasklistrl: if process == getpid[0:len(process)]: pid = int(getpid[29:34]) gotpid = True try: handle = win32api.OpenProcess(1, False, pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid)) except win32api.error as err: print(err) raw_input() sys.exit() if not gotpid: print("Could not get process pid.") raw_input() sys.exit() raw_input() sys.exit() prompt = raw_input("Which process would you like to kill? ") kill(prompt) 

That was just a paste of my process kill program I could make it a whole lot better but it is okay.

Источник

Оцените статью