8

I have a Python source file that looks like this:

import sys
x = sys.stdin.read()
print(x)

I want to invoke this source file by passing it to Python's stdin:

python < source.py

After source.py is read, I want the Python program to start reading from stdin (as shown above). Is this even possible? It appears that the interpreter won't process source.py until it gets an EOF, but if an EOF is received, then sys.stdin.read() won't work.

2 Answers 2

8

Use another FD.

import os

with os.fdopen(3, 'r') as fp:
  for line in fp:
    print line,

...

$ python < source.py 3< input.txt
2

If you don't want to do any fancy stuff on the command line beyond your example, you will have to redirect stdin to your terminal first thing in your python script. You can do that by invoking the command tty from within Python and getting the path to your tty, then changing sys.stdin to that.

import sys, os
tty_path = os.popen('tty', 'r').read().strip() # Read output of "tty" command
sys.stdin = open(tty_path, 'r') # Open the terminal for reading and set stdin to it

I believe that should do what you want.

EDIT:

I was mistaken. This will fail for your use case. You need some way of passing the current TTY path to the script. Try this instead:

import sys, os
tty_path = os.environ['TTY']
sys.stdin = open(tty_path, 'r') # Open the terminal for reading and set stdin to it

But you must then invoke the script slightly differently:

TTY=`tty` python < source.py

I should add that I think the sanest way—avoiding this issue entirely—would be to not redirect the script to python's stdin at all and just invoke it with python source.py.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.