gpt4 book ai didi

python - 在python中拆分一个变量表

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:11 25 4
gpt4 key购买 nike

在调用 lsof 之后,我正在寻找拆分每一行以获取表中每个单元格的字符串的通用方法,问题就来了,因为每次调用该命令时,每一列的大小都可能发生变化。

COMMAND     PID       USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
init 1 root cwd DIR 8,1 4096 2 /
kthreadd 2 root txt unknown /proc/2/exe
kjournald 42 root txt unknown /proc/42/exe
udevd 77 root cwd DIR 8,1 4096 2 /
udevd 77 root txt REG 8,1 133176 139359 /sbin/udevd
flush-8:1 26221 root cwd DIR 8,1 4096 2 /
flush-8:1 26221 root rtd DIR 8,1 4096 2 /
flush-8:1 26221 root txt unknown /proc/26221/exe
sudo 26228 root 5u unix 0xfff999002579d3c0 0t0 515611 socket
python 30077 root 2u CHR 1,3 0t0 700 /dev/null

最佳答案

不是解析 lsof 命令输出,而是安装 psutil 模块——它还具有跨平台的优势。

import psutil

def get_all_files():
files = set()
for proc in psutil.process_iter():
try:
files.update(proc.get_open_files())
except Exception: # probably don't have permission to get the files
pass
return files

print get_all_files()
# set([openfile(path='/opt/google/chrome/locales/en-GB.pak', fd=28), openfile(path='/home/jon/.config/google-chrome/Default/Session Storage/000789.log', fd=95), openfile(path='/proc/2414/mounts', fd=8) ... ]

然后您可以调整它以包括父进程和其他信息,例如:

导入 psutil

for proc in psutil.process_iter():
try:
fids = proc.get_open_files()
except Exception:
continue
for fid in fids:
#print dir(proc)
print proc.name, proc.pid, proc.username, fid.path

#gnome-settings-daemon 2147 jon /proc/2147/mounts
#pulseaudio 2155 jon /home/jon/.config/pulse/2f6a9045c2bc8db6bf32b2d7517969bf-device-volumes.tdb
#pulseaudio 2155 jon /home/jon/.config/pulse/2f6a9045c2bc8db6bf32b2d7517969bf-stream-volumes.tdb

关于python - 在python中拆分一个变量表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20349916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com