2

One can redirect input from a file with the < operator. So if I have a Python script, like:

name = input("Enter your name: ")
print("Hello", name)

Then I can put the input in a file like this:

Bob

And then run it with this:

$ python program.py < input.txt

When doing this, the output looks like this:

What is your name? Hello  Bob

Is there any way to have the input text appear on the screen as well, so that it looks the same as if you ran the program normally? For the example above, it would look like this:

What is your name? Bob
Hello Bob

The reason that I want this is because I am working on a book which has code examples, and I want to automate running the programs and having the output appear in the book. I don't know if this is possible, but it would make the whole process much easier since I can just write the programs, and setup the input files, and then have the rest happen automatically!

Thanks for reading!

  • Why not simply print out the variable after reading in ? Or you want specifically an external program ? – Sergiy Kolodyazhnyy Jan 19 '17 at 16:55
  • @Serg, I don't want to have to change the program since I want to include the code and the output into the book. – Ian Finlayson Jan 19 '17 at 17:13
  • Ah, understandable. I somehow doubt there's a way to peek on the stdin of a process, which is where your program reads from. At least not in the format that you ask – Sergiy Kolodyazhnyy Jan 19 '17 at 17:18
0

You could use an expect script to feed a given input file to a given python script:

ian.expect:

set script [lindex $argv 0]
set input  [lindex $argv 1]
set inputfh [open $input r]
spawn -noecho python $script
while {[gets $inputfh line] != -1} {
  expect {
    -re "(.+)" {
        send "$line\n"
    }
  }
}
close $inputfh
interact

ian.py:

name = input("Enter your name: ")
print("Hello", name)

input.txt:

"Jeff"

To execute any given python script with a given input file, run:

expect -f ian.expect ian.py input.txt

and you'll get:

$ expect -f ian.expect ian.py input.txt
Enter your name: "Jeff"
('Hello', 'Jeff')

I am not a TCL or Expect hacker, so I would welcome improvements to the script.

Example file and script with two inputs:

input.txt:

"Jeff"
14

ian.py:

name = input("Enter your name: ")
print("Hello", name)
age = input("Your age? ")
print("So, you are already " + str(age) + " years old, " + name + "!")

sample run:

$ expect -f ian.expect ian.py input.txt
Enter your name: "Jeff"
('Hello', 'Jeff')
Your age? 14
So, you are already 14 years old, Jeff!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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