How can I run a Python source from stdin, which itself reads from stdin?

I have a Python source file that looks like this:

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

I want to call this source file by passing it to Python stdin:

python < source.py

After reading, source.pyI want the Python program to start reading with stdin (as shown above). Is it possible? It seems that the interpreter does not process source.pyuntil it receives the EOF, but if the EOF is received, it sys.stdin.read()will not work.

+4
source share
2 answers

Use a different FD.

import os

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

...

$ python < source.py 3< input.txt
+6
source

- , stdin python script. , tty Python tty, sys.stdin .

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

, , .

EDIT:

. . - TTY script. :

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

script :

TTY=`tty` python < source.py

, , - - script python stdin python source.py.

+1

All Articles