Problems reading fra sys.stdin and later on duing raw_input

Carey Evans c.evans at clear.net.nz
Sun Mar 19 06:56:47 EST 2000


Peter Kristensen <pkr at netnord.dk> writes:

> I want to read a file from sys.stdin and then later on do a
> raw_input. But I get an error because sys.stdin is closed after the
> file is read.

[...]

> pkr at perm:~> echo -n "test" | /tmp/x.py 

stdin is still open, but it's connected to the output of echo, not the
terminal.  This is a limitation of any Unix program run in a pipeline
this way.

Some solutions I can see are:

 * Put the data in a file and pass the name of the file to your
   script, then open that file:

     lines = open(sys.argv[1]).readlines()

   This is probably the nicest solution, and the least prone to making
   wierd things happen if your script gets run differently.

 * Open /dev/tty to replace sys.stdin:

     sys.stdin = open('/dev/tty')
     a = raw_input('Prompt: ')

 * Redirect stdin to another file handle when you run your script, and
   read from that:

     sys.stdin = os.fdopen(3)
     a = raw_input('Prompt: ')

   $ (echo -n test | ./x.py) 3<&0

-- 
	 Carey Evans  http://home.clear.net.nz/pages/c.evans/

"*South Park* is another movie straight from the smoking pits of Hell."
                       - http://www.capalert.com/capreports/southpark.htm



More information about the Python-list mailing list