Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
Process info script for the fluxbox menu
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Desktop Environments
View previous topic :: View next topic  
Author Message
dr_strange
Guru
Guru


Joined: 16 Apr 2002
Posts: 480
Location: Cambridge, UK

PostPosted: Wed Feb 04, 2004 7:17 pm    Post subject: Process info script for the fluxbox menu Reply with quote

This is a reworked version of a script I did a while ago. It creates a submenu for the fluxbox menu showing running processes, with the possibility to kill, restart or terminate them. You'll have to include the output of the script into your normal flux menu, like this:

Code:

[submenu] (procinfo) {}
       [include] (/usr/share/commonbox/fbprocmenu.txt)
[end]


And this is the actual script, you can also download it from here.

Code:

#!/usr/bin/env python

#------------------------ process info script for fluxbox menu -----------------

import sys, os
from os.path import isdir, isfile, join
from time import sleep
def getprocesses():
    """Sort out process ids from /proc"""
    proccontent = os.listdir("/proc")
    dirsonly = [d for d in proccontent if isdir(join("/proc", d))]
    proclist = [elem for elem in dirsonly if elem[0] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']]
    proclist.sort()
    return proclist

def getprocinfo(procid):
    """Get info about an individual process."""
    procinfo = {}
    procpath = "/proc/%s/status" % procid
    statfile = open(procpath, 'r')
    procinfo["pid"] = procid
    for line in statfile.readlines():
        if "Name" in line:
            procinfo["Name"] = line.split(":")[1].strip()
        elif "State" in line:
            procinfo["State"] = line.split(":")[1].split(" ")[0].strip()
        else:
            break
    return procinfo

def makeprocdictlist(proclist):
    """Construct list of procinfo dictionaries"""
    procdictlist = [getprocinfo(pid) for pid in proclist]
    return procdictlist

while 1:
    procs = getprocesses()
    info = makeprocdictlist(procs)
    os.remove("/usr/share/commonbox/fbprocmenu.txt")
    try:
        outfile = open('/usr/share/commonbox/fbprocmenu.txt', 'w+')
        outfile.write('[begin]  (procinfo) {}\n')
        for elem in info:
            line = "[submenu]  ("+elem["Name"]+" "+elem["pid"]+" "+elem["State"]+") {}\n    [exec] (kill) {kill -9 "+elem["pid"]+"}\n   [exec]"\
      +" (restart) {kill -18 "+elem["pid"]+"}\n    [exec] (terminate) {kill -15 "+elem["pid"]+"}\n[end]\n"
            outfile.write(line)
        outfile.close()
        sleep(5)
    except IOError:
        print "Cannot create fbprocmenu file."
        sys.exit(0)


Here is a screenshot showing how it looks. I run it from my .xinitrc.
Back to top
View user's profile Send private message
christsong84
Veteran
Veteran


Joined: 06 Apr 2003
Posts: 1003
Location: GMT-8 (Spokane)

PostPosted: Wed Feb 04, 2004 10:04 pm    Post subject: Reply with quote

hey...that look's nifty and useful...will try it when I get home. :)
_________________
while(true) {self.input(sugar);} :twisted:
Back to top
View user's profile Send private message
Cosmosis
n00b
n00b


Joined: 13 Dec 2003
Posts: 59

PostPosted: Mon May 24, 2004 10:39 pm    Post subject: Reply with quote

Does anyone know how this would be used in openbox? I'm new to the *box's so I'm not too good with all of this yet. Anyone have any ideas?

-Tim
Back to top
View user's profile Send private message
OdinsDream
Veteran
Veteran


Joined: 01 Jun 2002
Posts: 1057

PostPosted: Tue May 25, 2004 12:31 am    Post subject: Reply with quote

This looks like a great idea, but I'm not sure I follow...

The script is an executable file, and it generates a text file as its output. How do I get the script to run every time I right-click and get my menu? Or, is the idea that you run the script, and -then- rightclick to operate on the items?

Where does the script go?
_________________
s/(?<!gnu\/)linux(?! kernel)/GNU\/Linux/gi

Don't blame me. I didn't vote for him.

http://john.simplykiwi.com
Back to top
View user's profile Send private message
ikaro
Advocate
Advocate


Joined: 14 Jul 2003
Posts: 2526
Location: Denmark

PostPosted: Wed May 26, 2004 5:53 pm    Post subject: Reply with quote

someone tried to make something similar:

http://fluxmod.dk/content.php?article.15
_________________
linux: #232767
Back to top
View user's profile Send private message
dr_strange
Guru
Guru


Joined: 16 Apr 2002
Posts: 480
Location: Cambridge, UK

PostPosted: Wed May 26, 2004 7:30 pm    Post subject: Reply with quote

OdinsDream wrote:
This looks like a great idea, but I'm not sure I follow...

The script is an executable file, and it generates a text file as its output. How do I get the script to run every time I right-click and get my menu? Or, is the idea that you run the script, and -then- rightclick to operate on the items?

Where does the script go?


The script updates the text file every 5 seconds (or more frequently, if you want, you can adjust the sleep() function).
All you have to do is to run the script (for instance from .xinitrc like fbprocmenu &) and include the generated txt file as a submenu in your flux menu.
_________________
shine on,

dr_strange

Set the Controls for the Heart of Gentoo
http://magenta.linuxforum.hu
Back to top
View user's profile Send private message
OdinsDream
Veteran
Veteran


Joined: 01 Jun 2002
Posts: 1057

PostPosted: Wed May 26, 2004 10:08 pm    Post subject: Reply with quote

Now I understand. This will be great, thanks!
_________________
s/(?<!gnu\/)linux(?! kernel)/GNU\/Linux/gi

Don't blame me. I didn't vote for him.

http://john.simplykiwi.com
Back to top
View user's profile Send private message
NewBlackDak
Guru
Guru


Joined: 02 Nov 2003
Posts: 512
Location: Utah County, UT

PostPosted: Thu May 27, 2004 2:12 am    Post subject: Reply with quote

You could also ad support to stop/start/restart all the services in /etc/init.d as easily. That would probably be very useful aswell.
_________________
Gentoo systems.
X2 4200+@2.6 - Athy
X2 3600+ - Myth
UltraSparc5 440 - sparcy
Back to top
View user's profile Send private message
swimmer
Veteran
Veteran


Joined: 15 Jul 2002
Posts: 1320
Location: Netherlands

PostPosted: Thu May 27, 2004 1:05 pm    Post subject: Reply with quote

NewBlackDak wrote:
You could also ad support to stop/start/restart all the services in /etc/init.d as easily. That would probably be very useful aswell.


WOW! This is a great idea!!!

Unfortunately I'm not familiar with Python :(
Could someone adopt this idea and bring it to life?

Would be great ...
Stefan
Back to top
View user's profile Send private message
OdinsDream
Veteran
Veteran


Joined: 01 Jun 2002
Posts: 1057

PostPosted: Thu May 27, 2004 1:21 pm    Post subject: Reply with quote

If I remember correctly, the init.d system now has a "status" option for each of the services, aside from start, stop, and zap.

I'm not at home right now, but from what I see, your code could easily be modified to first get a list of service names from the /etc/init.d/ folder, then loop through each one asking its status. I'll work on it this afternoon and see what I can come up with.
_________________
s/(?<!gnu\/)linux(?! kernel)/GNU\/Linux/gi

Don't blame me. I didn't vote for him.

http://john.simplykiwi.com
Back to top
View user's profile Send private message
numerodix
l33t
l33t


Joined: 18 Jul 2002
Posts: 743
Location: nl.eu

PostPosted: Thu May 27, 2004 7:24 pm    Post subject: Reply with quote

I'm not on fluxbox right now but is this similar to what comes with the default kahakai install? A submenu that shows processes, along with controls to admin them?
_________________
undvd - ripping dvds should be as simple as unzip
Back to top
View user's profile Send private message
dr_strange
Guru
Guru


Joined: 16 Apr 2002
Posts: 480
Location: Cambridge, UK

PostPosted: Thu May 27, 2004 7:25 pm    Post subject: Reply with quote

numerodix wrote:
I'm not on fluxbox right now but is this similar to what comes with the default kahakai install? A submenu that shows processes, along with controls to admin them?


Yes, I borrowed the idea from kahaki, although I did not study their code.
_________________
shine on,

dr_strange

Set the Controls for the Heart of Gentoo
http://magenta.linuxforum.hu
Back to top
View user's profile Send private message
fwerner
n00b
n00b


Joined: 27 Mar 2003
Posts: 46
Location: Germany / Freiburg

PostPosted: Fri May 28, 2004 5:44 pm    Post subject: slow Reply with quote

hm after the i run the script my fluxbox menu is incredible slow.

it builds the menu then the menu is hiding and then it comes back.

how can i speed it up?

another thing:
how can i make a "positive" or "negative" list.

because i dont want all process to be visible just a few....

anothing good thing would be to show how much cpu/ram usage the process actually have

i would do it myself but i dont know python...

beside that: VERY GOOD work.......

greetz
f.
Back to top
View user's profile Send private message
dr_strange
Guru
Guru


Joined: 16 Apr 2002
Posts: 480
Location: Cambridge, UK

PostPosted: Fri May 28, 2004 5:59 pm    Post subject: Reply with quote

It's curious; mine is not considerably slower.
_________________
shine on,

dr_strange

Set the Controls for the Heart of Gentoo
http://magenta.linuxforum.hu
Back to top
View user's profile Send private message
nadir-san
Apprentice
Apprentice


Joined: 29 May 2004
Posts: 174
Location: Ireland

PostPosted: Sat May 29, 2004 10:25 am    Post subject: Reply with quote

yea, I wrote the script on fluxmod.dk : i also got the idea from kahakai. What i'd really like to do is write an app like this in c, so it would be realtime, and fast. Im aware that its slow, but it was as much testing the idea as anything else.
It is a bit slow unfortunately, but im not so good with c and im struggeling trying to code it in c, If anyne is interested in giving it a shot ;).
One thing that really makest he menu slow is if you have a large (tansparent) menu with sub menus, then the transparancies overlap, this causes BIG slowdown, thats why I avoided that method, works fine if you dont use transparent menus.


ps. this is also my first post on the forums, heh, even though ive been using gentoo and lurking here for well over a year. Hello everybody :D
Back to top
View user's profile Send private message
bysse
n00b
n00b


Joined: 14 Jul 2004
Posts: 70
Location: Sweden

PostPosted: Thu Mar 10, 2005 4:41 pm    Post subject: Reply with quote

Great script! :D
I've modified it a bit and thought that someone might be interested.
The changes are:
* Only show processes that the current user have started
* Block certain processes from showing
* Make some processes uniqe, ie. only show one entry. (Some apps forks, like TS2 or linux dc++)

All this to reduce the size of the menu. Since I'm already using http://www.fms-engel.de/fbnews/ the menu is starting to get big :)
I've only tried it for one day so i realy don't know if it will work for everyone, but anyhow this is the code:
Code:
#!/usr/bin/env python

Refresh = 15
ExtendedInfo = True
BlockList = [ "bash", "x", "xinit", "startx", "firefox-bin", "fluxbox" ]
UniqueList = [ "teamspeak.bin", "xmms", "pymacs-services", "dcpp", "gftp-gtk"]
Output = "~/.fluxbox/fbprocmenu.txt"

#------------------------ process info script for fluxbox menu ------------------
import sys, os
from os.path import isdir, isfile, join, expanduser
from time import sleep
def getprocesses():
    """Sort out process ids from /proc"""
    proccontent = os.listdir("/proc")
    dirsonly = [d for d in proccontent if isdir(join("/proc", d))]
    proclist = [elem for elem in dirsonly if elem[0] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']]
    proclist.sort()
    return proclist

def getprocinfo(procid):
    """Get info about an individual process."""
    procinfo = {}
    procpath = "/proc/%s/status" % procid
    statfile = open(procpath, 'r')
    procinfo["pid"] = procid
    procinfo["uid"] = 0
    for line in statfile:
        if "Name" in line:
            procinfo["Name"] = line.split(":")[1].strip()
        elif "State" in line:
            procinfo["State"] = line.split(":")[1].split(" ")[0].strip()
        elif "Uid" in line:
            procinfo["uid"] = int(line.split(":")[1].strip().split("\t")[0])           
        elif "Gid" in line:
            break
    statfile.close()
    return procinfo

def makeprocdictlist(proclist):
    """Construct list of procinfo dictionaries"""
    uid = os.getuid()
    procdictlist = []
    duplicatelist = []
    for pid in proclist:
        try:
            pf = getprocinfo(pid)
            if pf['uid'] == uid:
                name = pf['Name'].lower()
                if not name in BlockList:
                    if name in UniqueList:
                        if not name in duplicatelist:
                            duplicatelist.append(name)
                            procdictlist.append(pf)                       
                    else:
                        procdictlist.append(pf)
        except IOError:
            pass

    procdictlist.sort(lambda a,b: cmp(a['Name'].lower(), b['Name'].lower()))
    return procdictlist

def setextended(list):
    user = os.getenv("USER")
    cmd = "ps aux | awk '/"+user+"/ { printf(\"%s %s %s\",$2,$8,$9); for(i=11;i<=NF;i++) printf(\" %s\",$i); printf(\"\\n\") }'"
    stdin, stdout = os.popen2(cmd)

    info = {}
    for line in stdout:
        lst = line.split(' ')
        cmdline = " ".join(lst[3:]).strip()
        info[lst[0]] = {'mode':lst[0], 'start':lst[2], 'cmd':cmdline}

    for elem in list:
        try:
            elem.update(info[elem['pid']])
        except Exception: pass
   
while True:
    Output = expanduser(Output)
    procs = getprocesses()
    info = makeprocdictlist(procs)
    if ExtendedInfo: setextended(info)
   
    try:os.remove(Output)
    except OSError: pass
    try:
        outfile = open(Output, 'w+')
        outfile.write('[begin]  (procinfo) {}\n')
        if ExtendedInfo:
            for elem in info:
                try:
                    line = "[submenu]  ("+elem['start']+' '+elem["Name"]+" "+elem["mode"]+") {}\n"
                    line+= "    [exec] (kill -9 "+elem["pid"]+") {kill -9 "+elem["pid"]+"}\n"
                    line+= "    [exec] (cmd: "+elem['cmd']+") {}\n"               
                    line+= "[end]\n"
                except KeyError:
                    line = "[submenu]  ( --:-- "+elem["Name"]+" "+elem["State"]+") {}\n    [exec] (kill -9 "+elem["pid"]+") {kill -9 "+elem["pid"]+"}\n[end]\n"
                outfile.write(line)
        else:
            for elem in info:           
                line = "[submenu]  ("+elem["Name"]+" "+elem["pid"]+" "+elem["State"]+") {}\n    [exec] (kill) {kill -9 "+elem["pid"]+"}\n[end]\n"
                outfile.write(line)
        outfile.close()
        sleep(Refresh)
    except IOError:
        print "Cannot create "+Output+" file."
        sys.exit(0)

Back to top
View user's profile Send private message
nadir-san
Apprentice
Apprentice


Joined: 29 May 2004
Posts: 174
Location: Ireland

PostPosted: Fri Mar 18, 2005 2:37 pm    Post subject: Reply with quote

ahh, your the man, you rewrote it in python, I havnt tried it yet cause I'm at work, but ill give it a shot when i go home.
ok thats cool, thats like all gentoo friendly and stuff, but flux is all c, i wonder would it be better to rewrite it in c
or do you think it would be cool to go modding fluxbox with python?
im not sure, I'm not sure which direction to take.
Like flux <3 c
and gentoo <3 python

/me love python syntax
but /me love c's speed.

hrm, O_o
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Desktop Environments All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum