[Tutor] regular expression
Kent Johnson
kent37 at tds.net
Thu Aug 3 19:46:55 CEST 2006
arbaro arbaro wrote:
> Hello,
>
> I'm trying to mount an usb device from python under linux.
> To do so, I read the kernel log /proc/kmsg and watch for something like:
> "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan
> complete"
>
> When I compile a regular expression like:
> "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
You should use raw strings for regular expressions that contain \
characters.
> It is found. But I don't want the <\d+>\s or '<6> ' in front of the
> path, so I tried:
> "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
> But this way the usb device path it is not found.
You are using re.match(), which just looks for a match at the start of
the string. Try using re.search() instead.
http://docs.python.org/lib/matching-searching.html
Kent
>
> So what i'm trying to do is:
> - find the usb device path from the kernel log with the regular
> expression.
> - Determine the start and end positions of the match (and add /disc or
> /part1 to the match).
> - And use that to mount the usb stick on /mnt/usb -> mount -t auto
> match /mnt/usb
>
> If anyone can see what i'm doing wrong, please tell me, because I
> don't understand it anymore.
> Thanks.
>
> Below is the code:
>
> # \d+ = 1 or more digits
> # \s = an empty space
>
> import re
>
> def findusbdevice():
> ''' Returns path of usb device '''
> # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel
> message.
> # Somehow I can't read /proc/kmsg directly.
> kmsg = open('/log/kmsg', 'r')
> r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
> #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
> for line in kmsg:
> if 'usb-storage' in line and r.match(line):
> print 'Success', line
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list