使用终端命令登录后,如何查看最近正在运行的应用程序和进程。
以下脚本列出了所有进程,并将它们拆分为应用程序和其他进程。
作为应用程序的定义,我练习从一个.desktop
文件启动该过程(因为实际上所有应用程序都由一个.desktop
文件表示),并且该.desktop
文件显示在Dash中(.desktop
文件没有行:)NoDisplay=true
。
要做的工作:
脚本实际上是从桌面文件中找到的命令的(-的最后一部分)以及它可能引用的可能符号链接中找到的信息中得出应用程序的过程名称的(例如,LibreOffice
> process的情况下)名称:)soffice.bin
。但是,在某些情况下,应用程序是从.desktop
文件中调用的远程脚本运行的。在这些情况下,该过程将不会被视为应用程序。
该脚本给出如下输出:
Processes, related to applications:
PID TTY TIME CMD
1933 ? 00:03:55 firefox
18091 ? 00:00:00 dia
18162 ? 00:00:01 soffice.bin
31167 ? 00:00:06 alarm-clock-app
31174 ? 00:00:09 nautilus
31301 ? 00:00:20 dropbox
31998 ? 00:01:35 idle3
Other processes:
PID TTY TIME CMD
1 ? 00:00:01 init
2 ? 00:00:00 kthreadd
3 ? 00:00:02 ksoftirqd/0
5 ? 00:00:00 kworker/0:0H
7 ? 00:00:15 rcu_sched
8 ? 00:00:08 rcuos/0
等等...
剧本
#!/usr/bin/env python3
import os
import subprocess
def createlist_appcommands():
dtfile_dir = "/usr/share/applications"
dtfile_list = [item for item in os.listdir(dtfile_dir) if item.endswith(".desktop")]
commands = []
for item in dtfile_list:
try:
with open(dtfile_dir+"/"+item) as data:
searchlines = data.readlines()
command = [line for line in searchlines if line.startswith("Exec=")
and not "NoDisplay=true\n" in searchlines
][0].replace("Exec=", "").replace("\n", "").split("/")[-1].split(" ")[0]
commands.append(command)
except Exception:
pass
return commands + [trace_symlinks(item) for item in commands if not trace_symlinks(item)== None]
def trace_symlinks(command):
target = subprocess.Popen(["which", command], stdout=subprocess.PIPE)
location = (target.communicate()[0].decode("utf-8")).split("\n")[0]
check_filetype = subprocess.Popen(["file", location], stdout=subprocess.PIPE)
filetype = (check_filetype.communicate()[0].decode("utf-8")).split("\n")[0]
if "symbolic link" in filetype:
return filetype.split("/")[-1].replace("' ", "")
else:
pass
def createlist_runningprocs():
processesb = subprocess.Popen(["ps", "-e"], stdout=subprocess.PIPE)
process_listb = (processesb.communicate()[0].decode("utf-8")).split("\n")
linked_commands = [(item, item[24:]) for item in process_listb][1:]
applist = createlist_appcommands()
print("Processes, related to applications:\n PID TTY"+" "*10+"TIME CMD")
matches = []
for item in applist:
for i in range(0, len(linked_commands)):
if item[:15] in linked_commands[i][1] and len(item[:15])/len(linked_commands[i][1]) > 0.5:
matches.append(i)
matches = sorted(matches)
for i in range(0, len(linked_commands)):
if i in matches:
print(linked_commands[i][0])
print("\nOther processes:\n PID TTY"+" "*10+"TIME CMD")
for i in range(0, len(linked_commands)):
if not i in matches:
print(linked_commands[i][0])
createlist_runningprocs()
如何使用
将脚本复制到一个空文件中,另存为processes.py
,然后通过以下命令运行该脚本:
python3 /path/to/processes.py
编辑:更新了我的答案,重写了脚本。
改进之处:
(很多)更好的性能
脚本现在可以跟踪和识别通过符号链接(可能具有另一个进程名称)启动的应用程序。尽管例外总是可能的,但现在应该很少见了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句