这应该很简单,但我只是没有看到它。
如果我有进程ID,我该如何使用它来获取有关进程的信息,例如进程名称。
答案 0 :(得分:20)
在Linux下,您可以阅读proc文件系统。文件/proc/<pid>/cmdline
包含命令行。
答案 1 :(得分:14)
尝试PSUtil - &gt; https://github.com/giampaolo/psutil
我记得在Windows和Unix上正常工作。
答案 2 :(得分:1)
适用于Windows
无需下载任何模块即可在您的计算机上获取所有程序的方法:
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)
如果您只是想要一个程序或所有具有相同名称的程序,并且您想要终止该过程或其他内容:
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)
这只是我的进程终止程序的一个粘贴我可以让它变得更好但是没关系。
答案 3 :(得分:1)
使用psutil,这是我可以给您的最简单的代码:
import psutil
# The PID ID of the process needed
pid_id = 1216
# Informations of the Process with the PID ID
process_pid = psutil.Process(pid_id)
print(process_pid)
# Gives You PID ID, name and started date
# psutil.Process(pid=1216, name='ATKOSD2.exe', started='21:38:05')
# Name of the process
process_name = process_pid.name()
答案 4 :(得分:0)
试试这个
def filter_non_printable(str):
ret=""
for c in str:
if ord(c) > 31 or ord(c) == 9:
ret += c
else:
ret += " "
return ret
#
# Get /proc/<cpu>/cmdline information
#
def pid_name(self, pid):
try:
with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile:
return filter_non_printable(pidfile.readline())
except Exception:
pass
return