How do I start a Python script with some input already waiting in stdin. For example, say I have this simple script located in main.py
, using Python3:
mystr = input()
print(mystr)
If you just called python3 main.py
from the terminal, the script would pause and wait for you to type something. After hitting enter it would continue and print out what you typed. But is there a way to place something into stdin before the script executes? That way the script wouldn't pause, it would accept what's already there. I was envisioning something like:
python3 main.py | my string
but that doesn't work.
Note that I am not asking about command line arguments: I am writing an application which will have to take input from stdin, so I am looking for a convenient solution to test out that environment.
This doesn't depend on the fact that a Python script is involved, and the same methods work for feeding bytes into the stdin of any process started under bash (you might want to add a bash
tag to your question to reflect this):
To feed a short string into it
echo 'my string' | python3 main.py
To feed a file of sample input into it
cat my_input | python3 main.py
You can also feed a file like this
python3 mail.py < my_input
[Note: Some people like to spend a lot of time arguing that method 3 is better than method 2, (search for 'useless use of cat' if you're interested), but I've come to prefer method 2 (for reasons that are beyond the scope of your question). Use whichever makes the most sense to you.]