在 python 中读取 /proc/$pid/status 时出错

Error while reading /proc/$pid/status in python

我必须阅读 /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'

如何更正此问题?

您声明了一个名为 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)