14

My Python program requests some user input:

n = int(input())
for i in range(n):
    s = input()
    # ...

For debugging purposes, I would like to create a test input.txt file like this:

3
string1
string2
string3

so that I need not to manually enter data from the keyboard every time I launch it for debug.

Is there any way to get input() from text file, not from keyboard (without changing program code).

I am using Wing Personal as a dev tool.

Update

I know for sure, that there exist bots which are able to test python programs passing various inputs and comparing output with known answers. I guess these bots do not hit the keyboard with iron fingers. Maybe they use command-line tools to pass input.txt to the Python so that it reads input() from that file, not from keyboard. I would like to learn how to do it.

0

4 Answers 4

23

Input reads from Standard input so if you use bash you can redirect stdin to a file

without changing your code

in bash you would run something like

cat textfile | programm.py

or

< textfile programm.py
Sign up to request clarification or add additional context in comments.

4 Comments

OP asked for python?
he also asks (without changing program code). so i provided a method for changing standard input without touching the code
standing your ground, I like it!
I think you meant, cat textfile | python programm.py
10

I've noticed that none of these solutions redirects the stdin from Python. To do that, you can use this snippet:

import sys
sys.stdin = open('input.txt', 'r')

Hopefully, that helps you!

Comments

1

You can read the file into a list like this:

 with open('filename.txt', 'r') as file:
     input_lines = [line.strip() for line in file]

s would be data in index i.

n = int(input())
for i in range(n):
    s = input_lines[i]
    # ...

Make sure your py file is in the same dir as your txt file.

Comments

0

You can create a test.py file which is used to run your test. In the test.py, you will read the content of input.txt and import the programming.

For example, in test.py file.

import main_code
with open('input.txt', 'r') as file:
   lines = file.readlines()

for line in lines:
   s = line

"""
working with the input.
""" 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.