Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string as stdin to python script from command line interface

Tags:

python

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

like image 430
kamal Avatar asked Apr 27 '11 11:04

kamal


People also ask

How do you pass a file path as a command line argument in Python?

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.


2 Answers

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
like image 71
Lauritz V. Thaulow Avatar answered Sep 19 '22 13:09

Lauritz V. Thaulow


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.

like image 25
Senthil Kumaran Avatar answered Sep 17 '22 13:09

Senthil Kumaran