在python中读取/proc/$pid/status时出错
我必须阅读在python中读取/proc/$pid/status时出错,python,file-read,Python,File Read,我必须阅读/proc/pid/status文件以提取NSpid字段,如下所示: user@user-HP-Pavilion-Notebook:~$ cat /proc/5979/status | grep NSpid NSpid: 5979 1417 我必须从中提取1417 我试过以下方法: print("Traversing tree") pid=5947 for c in psutil.Process(pid).children(True): cpid=
/proc/pid/status
文件以提取NSpid
字段,如下所示:
user@user-HP-Pavilion-Notebook:~$ cat /proc/5979/status | grep NSpid
NSpid: 5979 1417
我必须从中提取1417
我试过以下方法:
print("Traversing tree")
pid=5947
for c in psutil.Process(pid).children(True):
cpid=c.pid
print(str(c.pid))
with open("/proc/cpid/status",'r') as origin_file:
for line in origin_file:
line = re.findall(r'NSpid', line)
if line:
line = line[0].split('"')[1]
print(line)
break
该程序遍历整个进程树,并为每个试图从状态文件提取NSpid的子进程遍历。
但我得到了以下错误:
Traversing tree
5979
Traceback (most recent call last):
File "cmp.py", line 48, in <module>
with open("/proc/cpid/status",'r') as origin_file:
FileNotFoundError: [Errno 2] No such file or directory: '/proc/$cpid/status'
遍历树
5979
回溯(最近一次呼叫最后一次):
文件“cmp.py”,第48行,在
以open(“/proc/cpid/status”,'r')作为源文件:
FileNotFoundError:[Errno 2]没有这样的文件或目录:'/proc/$cpid/status'
如何更正此问题?您声明了一个名为
cpid
的变量,如我所见,您希望在文件路径中使用该变量,因此可以使用f
字符串
cpid=c.pid
print(str(c.pid))
with open(f"/proc/{cpid}/status") as origin_file:
...
我仍然不确定要提取的值是什么,因此这是我的解决方案,我搜索了流程的NSpid
属性,并获取了它的值
...
cpid = c.pid
with open(f"/proc/{cpid}/status") as origin_file:
for line in origin_file.read().splitlines():
if line.split()[0] == 'NSpid:':
print(line.split()[2])
break
如果要提取整个属性,只需更改print
函数
# before
print(line.split()[2]) # changed this index from [1] to [2]
# after
print(line)
您声明了一个名为
cpid
的变量,如我所见,您希望在文件路径中使用该变量,因此可以使用f
字符串
cpid=c.pid
print(str(c.pid))
with open(f"/proc/{cpid}/status") as origin_file:
...
我仍然不确定要提取的值是什么,因此这是我的解决方案,我搜索了流程的NSpid
属性,并获取了它的值
...
cpid = c.pid
with open(f"/proc/{cpid}/status") as origin_file:
for line in origin_file.read().splitlines():
if line.split()[0] == 'NSpid:':
print(line.split()[2])
break
如果要提取整个属性,只需更改print
函数
# before
print(line.split()[2]) # changed this index from [1] to [2]
# after
print(line)
这不是一条完整的路径吗?如果没有,那么它将是怎样的?@r0ei文件在那里看到命令行结果它能够grep 5979是5947@r0ei你的答案打印了一条空行,这不是完整路径吗?如果没有,那么它将是怎样的?@r0ei文件在那里看到命令行结果它能够grep 5979是5947@r0ei你的答案打印一条空行这就是它现在打印的内容:遍历树5979[]5980[]5981[]5982[]5986[]5987[]5988[]5992[]5995[]5996[]5997[]5998[]6002[]6003[]6004[]6005[]6006[] 6120 [] 6123@user13145713这是你的输出?这是你想要得到的?如果不是,例外的输出是什么?是的,这是我的输出现在行将是这样的:NSpid:5979 1417,我只想提取1417这是它现在打印的内容:遍历树5979[]5980[]5981[]5982[]5986[]5987[]5988[]5992[]5995[]5996[] 5997 [] 5998 [] 6002 [] 6003 [] 6004 [] 6005 [] 6006 [] 6120 [] 6123@user13145713这是您的输出?这是您想要得到的?如果不是,例外的输出是什么?是的,这是我的输出现在行将是这样的:NSpid:5979 1417,我只想提取1417