[Tutor] Starting to write a scanf-like module for Python
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sun Aug 15 03:33:44 CEST 2004
Hi everyone,
I thought it might make a nice weekend project to write scanf for Python;
it's nowhere near done yet, but it's sorta working... *grin*
http://hkn.eecs.berkeley.edu/~dyoo/python/scanf.py
I want to gauge some input from folks on the list to see if this might be
useful for folks. A lot of programming assignments will assume that the
implementing language is something like C, and with it, taylor the input
to take advantage of C's scanf() input function.
But Python doesn't have this by default, and it's slightly annoying to
have to manually do a lot of input stream munging to simulate something
simple like:
scanf("%d %d", &x, &y); /* C code to read two integers, with any
amount of whitespace between the two */
And regular expression solutions to this have always felt a little off,
since Python's regular expression library works on strings, not file
streams.
So that's what this 'scanf' module is supposed to help with. Here's an
example of it in action:
###
>>> from scanf import scanf
>>> scanf("%d %d")
3
1
(3, 1)
>>> scanf("%s%s")
hello
world
('hello', 'world')
>>> scanf("%d / %d / %d")
2004/08/14
(2004, 8, 14)
>>> scanf.scanf("%s hello")
danny hello
('danny',)
>>> scanf.scanf("%s hello")
danny hi
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "scanf.py", line 146, in scanf
return bscanf(STDIN, formatString)
File "scanf.py", line 162, in bscanf
return parser(buffer)
File "scanf.py", line 310, in f
raise IncompleteCaptureError, (e, tuple(results))
scanf.IncompleteCaptureError: (<scanf.FormatError instance at 0x653a0>,
('danny',))
###
It doesn't support everything that C's scanf can do yet, and probably
never will. I'm just trying to implement just enough to make it easy to
do the stuff from Programming Challenges without having to worry too much
about input/output. But if there's something that folks feel really
should be in the module, I'll try to be receptive.
Hope this helps!
More information about the Tutor
mailing list