Very newbie programming

Maric Michaud maric at aristote.info
Sat Jun 10 13:23:29 EDT 2006


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



More information about the Python-list mailing list