问题描述
我正在尝试编写一个程序来查找进程的所有父进程。
我的代码是这样的:
import psutil
def print_process_info(proc_obj,proc_order=1):
with proc_obj.oneshot():
print(f'process order {proc_order}')
print('name: ',proc_obj.name())
print('pid: ',proc_obj.pid)
print('status: ',proc_obj.status())
print('exe: ',proc_obj.exe())
try:
parent_pid = proc_obj.ppid()
except Exception as e:
raise e
else:
print('parent id: ',parent_pid)
try:
parent = proc_obj.parent()
#parent = psutil.Process(parent_pid)
except psutil.NoSuchProcess:
print(f'Unable to find parent,{parent_pid}')
else:
if parent is not None:
print('\nPrinting parent process info\n')
proc_order += 1
print_process_info(parent,proc_order=proc_order)
else:
print(f'Unable to find parent,{parent_pid}')
p = psutil.Process()
环境:Python 3.7、Psutil 5.8、Windows 10
我注意到的问题:
一旦这个程序进入我认为的顶级, 它仍然返回父 pid - 但不会访问父进程。
例如,运行这段代码会返回类似这样的日志:
- 蟒蛇,pid 49000,ppid 45636
- 蟒蛇,pid 45636,ppid 40208
- bash,pid 40208,ppid 21072
- bash,pid 21072,ppid 54124
- cmd,pid 54124,ppid 46588
- git-bash,pid 46588,ppid 10116
- 资源管理器,pid 10116,ppid 10036
然后,找不到pid为10036的进程。
使用 .parent() 只返回 None
,
而 .Process(ppid) 返回异常 NoSuchProcess
。
我对问题原因的假设是访问权限, 但我很困惑,因为 .ppid() 应该返回一个描述拒绝访问的异常,如果是这样的话。这与 .parent() 或 .Process(ppid) 相同。
如果这确实是与访问权限相关的问题,
- 为什么不这么说?
- 有没有办法获得访问权限?
如果不是,有人能解释一下可能是什么问题吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)