Ascii Menu I/O redirection
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Sep 20 10:25:30 EDT 2008
On Sat, 20 Sep 2008 23:14:26 +0200, Hendrik van Rooyen wrote:
> class console(object):
> """
> This spoofs a single file like object, using stdout & - in
> (Minimalistic proof of concept implementation) """
>
> def __init__(self):
> self.read = sys.stdin.read
> self.readline = sys.stdin.readline
> self.write = sys.stdout.write
> self.flush = sys.stdout.flush
> self.closeout = sys.stdout.close # keep references to close
> self.closein = sys.stdin.close
>
> def close(self):
> self.closein()
> self.closeout()
I'm not sure that closing stdin and stout are a good idea. This could
have side-effects for other parts of your program, and will almost
certainly end badly if you're running in the interactive interpreter.
Other than that, what you've done seems reasonable, although since every
instance of console() has the same state, I'd write it slightly
differently:
class console(object):
"""
This spoofs a single file like object, using stdout & - in
(Minimalistic proof of concept implementation)
"""
read = sys.stdin.read
readline = sys.stdin.readline
write = sys.stdout.write
flush = sys.stdout.flush
closeout = sys.stdout.close
closein = sys.stdin.close
@classmethod
def close(cls):
cls.closein()
cls.closeout()
[...]
> Questions are:
>
> Is this a reasonable way of doing this kind of thing? Is there a
> canonical or better way of doing it? Am I missing something?
It seems to me that you might have been better off to write your program
to take two files, an input and an output, instead of forcing both to go
to the same file.
if 'serial' in sys.argv: # for RS-232 i/o to terminal
infile = open('/dev/ttyS0','r+b')
outfile = infile
else: # console i/o
infile = sys.stdin
outfile = sys.stdout
Hope this helps.
--
Steven
More information about the Python-list
mailing list