Very newbie programming

T

TheSaint

Hello!

Is there a more pythonic way to implement the following program:

8<--------------8<--------------8<--------------8<--------------

#! /usr/bin/env python

import os
import sys
a = os.listdir('/media')

# no mount dirs were found, exit nicely

if len(a) == 0:
sys.exit(0)

# Maybe collecting the arguments via command line
# will make the program more flexible

mnt = open("/etc/mtab")
ptn = open("/proc/partitions")
dskt = '/home/user/Desktop/'

c =[]

# Filling the c with the list of devices which are recorded to be mounted

d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
off
d = map((lambda a: a.split()[:1]),d) # only the first info column is used

[c.append(str(a)[2:-2]) for a in d]

# checking against /proc/partitions to see if there're mountpoints without
# corresponding partition which has been removed from the list
# ALL mountpoints with available partition will be removed from the list

x = ptn.readlines()
for a in x[2:]:
b = a.split()[-1]
for d in c:
if b == d.rsplit('/',1)[-1]:
c.remove(d)

if len(c) != 1:
sys.exit(0) # if none or more than one match exit

cmnd = str(c)[2:-2]
err = os.system('umount ' + cmnd)
a = os.listdir(dskt)

#retrieve the info from the KDE desktop icons

for i in a:
if 'desktop' not in i: continue
y = open(dskt + i)
d = y.readlines()
for x in d:
if 'URL=/media' not in x: continue
icon = i
dvc = x[11:-1]
break

err += os.system('rm -f ' + dskt + icon)
err += os.system('rmdir /media/' + dvc)
sys.exit(err)
# if something went wrong exit with high number
8<--------------8<--------------8<--------------8<--------------

I still have a long learnig curve, please give some advise in order to make
the program a bit faster o nicer :)

F
 
A

Alexander Schmolck

TheSaint said:
# Filling the c with the list of devices which are recorded to be mounted

d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
off
d = map((lambda a: a.split()[:1]),d) # only the first info column is used

Just focusing one one detail:

1. you don't need the parens around the lambda

2. you can just write the above as

d = [a.split()[:1] for a in mnt if a.startswith('/d')]


'as
 
M

Maric Michaud

Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
Hello!
Hi,
Is there a more pythonic way to implement the following program:
I'll try to make some suggestions.
8<--------------8<--------------8<--------------8<--------------

#! /usr/bin/env python

import os
import sys
a = os.listdir('/media')
begin using more explicit variable names.

medias = os.listdir('/media')
# no mount dirs were found, exit nicely

if len(a) == 0:
sys.exit(0)
or

if not medias : sys.exit(0)

and I generally avoid creating names I use only once, so :

if not os.listdir('/media') :
sys.exit(0)
# Maybe collecting the arguments via command line
# will make the program more flexible

mnt = open("/etc/mtab")
ptn = open("/proc/partitions")
dskt = '/home/user/Desktop/'

c =[]

# Filling the c with the list of devices which are recorded to be mounted

d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
off
d = map((lambda a: a.split()[:1]),d) # only the first info column is used

[c.append(str(a)[2:-2]) for a in d]

# checking against /proc/partitions to see if there're mountpoints without
# corresponding partition which has been removed from the list
# ALL mountpoints with available partition will be removed from the list
There more expressive or more direct ways of doing all these, I like one
liners (but a two steps can be more clear) :

devices = [ e.split()[0] for e in open("/etc/mtab") if e.startswith('/d') ]

x = ptn.readlines()
for a in x[2:]:
b = a.split()[-1]
for d in c:
if b == d.rsplit('/',1)[-1]:
c.remove(d)

this time we cut in two steps but this also just filtering.

partitions = [ e.split()[-1] for e in open("/proc/partitions").readlines()
[2:] ]
devices = [ e for e in devices if e.split('/')[-1] in partitions ]
if len(c) != 1:
sys.exit(0) # if none or more than one match exit

cmnd = str(c)[2:-2]
err = os.system('umount ' + cmnd)

why ?

os.system('umount "%s"' % devices[0])
a = os.listdir(dskt)

#retrieve the info from the KDE desktop icons

for i in a:
if 'desktop' not in i: continue
y = open(dskt + i)
d = y.readlines()
for x in d:
if 'URL=/media' not in x: continue
icon = i
dvc = x[11:-1]
break

this will do exactly the same

for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop' in
e) :
for line in icon_file :
if 'URL=/media' in line :
icon = icon.name
dvc = line[11:-1]
break



--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
 
T

TheSaint

Maric said:
Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
begin using more explicit variable names.

Frankly it's a very rooted way of programming, since C64 basic :)

A part of this, how python catch variables, the longer the slower, isn't it?
Even supposing to use a set of similar name of variables.
Of course nowadays this operations ending up in term of msecs. I still be
used in old fashion. I'll change it by the time of necessity.
and I generally avoid creating names I use only once, so :

if not os.listdir('/media') :

Great idea and common sense :)

There more expressive or more direct ways of doing all these, I like one
liners (but a two steps can be more clear) :

I like the clearer. I think python does it as we would think it off.
this time we cut in two steps but this also just filtering.

I found the bothering of having to remove the trailing LF "\n". Perhaps need
some new function to strip the last LF, for all of the files opened.
why ?

os.system('umount "%s"' % devices[0])

I wasn't able to handle more than one mount a time. Furthermore, the script
is executed every minute in a cron schedule. I don't expect to remove
devices in so fast fashion :)
BTW, this operation is necessary because the kernel doesn't do it on its
own, for pendrives and Compact Flash into PCMCIA socket. (Kernel 2.6.15
actually)
One more point, suppose to use multiple removal, how will it remove also the
icon(s) from the KDE desktop?
Good to applying myself on studying on it :)
this will do exactly the same

for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop'
in e) :
for line in icon_file :
if 'URL=/media' in line :
icon = icon.name
dvc = line[11:-1]
break
A simple question, how do I'll get out of all loops, once found the right
result?

F
 
G

George Sakkis

TheSaint said:
Frankly it's a very rooted way of programming, since C64 basic :)

If by 'rooted' you mean old enough, so is 'goto'... Except perhaps for
iteration variables ("for i in xrange(10)"), always use names that mean
something; you (and anyone else that might have to read your code) will
thank yourself for doing so if you have to go back at this code a few
months later.
this will do exactly the same

for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop'
in e) :
for line in icon_file :
if 'URL=/media' in line :
icon = icon.name
dvc = line[11:-1]
break
A simple question, how do I'll get out of all loops, once found the right
result?

You can set a boolean "found" flag to False, make it True in the if
block, check it in the outer loop and break if it is True. For this
case though I'd use the fileinput module to iterate over the lines of
all files directly (http://docs.python.org/lib/module-fileinput.html):

from fileinput import FileInput

instram = FileInput([dskt+e for e in os.listdir(dskt) if 'desktop' in
e])
for line in instream:
if 'URL=/media' in line :
icon = instream.filename()
dvc = line[11:-1]
break

Btw, you can delete a file or directory with os.unlink and os.rmdir,
respectively; no need for os.system.

George
 
T

TheSaint

Maric said:
Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
devices = [ e for e in devices if e.split('/')[-1] in partitions ]

This is _not_ the expected result :)

is missing a not as :
devices = [ e for e in devices if e.split('/')[-1] *not* in partitions ]
if len(c) != 1:
sys.exit(0) # if none or more than one match exit

cmnd = str(c)[2:-2]
err = os.system('umount ' + cmnd)

why ?

os.system('umount "%s"' % devices[0])
for line in icon_file :
if 'URL=/media' in line :
icon = icon.name
dvc = line[11:-1]
break

The question is correct, I should go a step further. But as it will unmount
multiple (ghost) partitions it should also remove the icons from the
desktop as well. So I'm bit confused how to remove *each* icon, unless do
it into the "for" loop.
I'd like to get the search as fast as possible and solve the appropriate
icon with the right device, after all :)
Suppose to have the pendrive and the Compact Flash, which both are mounted
in /media, what will be removed syncronized with its mount?
I didn't get this problem so deep as long as I just considered to use one
device at time.

F
 
T

TheSaint

George said:
If by 'rooted' you mean old enough, so is 'goto'...

I was meaning a sort of (very) old style of programming. In fact I wrote
some few hundreds lines on my own, but probably memory was much better
the :)
will
thank yourself for doing so if you have to go back at this code a few
months later.

I have to admit that's purely true :)
You can set a boolean "found" flag to False, make it True in the if

Thank you to point it out, I forgotten such solution. BTW I was on the way
of an "try/exept". But I should go back study the corect use :)
from fileinput import FileInput

I'll read the manual (as you pointed hereby) and I think I can read the
entire directory file by file.
Btw, you can delete a file or directory with os.unlink and os.rmdir,
respectively; no need for os.system.

I still on learning, you know? :)
Reading is the way to solve some problem, and your suggestions (you all) are
very precious.

F
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,158
Latest member
Vinay_Kumar Nevatia
Top