Currently, I am using the following command to do this
$ python scriptName.py <filePath
This command uses "<" to stdin the file to script. and it works fine, I can use sys.stdin.read to get the file data.
But, what if I want to pass file data as a string, I don't want to pass file path in operator "<".
Is there is anyway, where I can pass String as stdin to a python script?
Thanks, Kamal
To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions.
The way I read your question, you currently have some file abc.txt
with content
Input to my program
And you execute it this way:
python scriptName.py <abc.txt
Now you no longer want to go by way of this file, and instead type the input as part of the command, while still reading from stdin. Working on the windows command line you may do it like this:
echo Input to my program | python scriptName.py
while on Linux/Mac you'd better quote it to avoid shell expansion:
echo "Input to my program" | python scriptName.py
This only works for single-line input on windows (AFAIK), while on linux (and probably Mac) you can use the -e switch to insert newlines:
echo -e "first line\nsecond line" | python scriptName.py
There is raw_input
which you can use make the program prompt for input and you can send in a string. And yes, it is mentioned in the first few pages of the tutorial at http://www.python.org.
>>> x = raw_input()
Something # you type
>>> x
'Something'
And sending the input via <
the shell redirection operation is the property of shell and not python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With