开发者

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

开发者 https://www.devze.com 2023-03-01 13:38 出处:网络
Currently, I am using the following command to do this $ python scriptName.py <filePath This command uses \"<\" to stdin the file to script.

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 a开发者_如何学Gos stdin to a python script?

Thanks, Kamal


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.


I could be wrong, but the way that I read the OP's question, I think he may currently be calling an os command to run a shell script inside of his python script, and then using a < operator to pass a file's contents into this shell script, and he is just hard coding the < and filename.

What he really desires to do is a more dynamic approach where he can pass a string defined in Python to this shell script.

If this is the case, the method I would suggest is this:

import subprocess;

script_child = subprocess.Popen(['/path/to/script/myScript.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

stdout, stderr = clone_child.communicate("String to pass to the script.")

print "Stdout: ", stdout
print "Stderr: ", stderr

Alternatively, you can pass arguments to the script in the initial Popen like so:

script_child = subprocess.Popen(['/path/to/script/myScript.sh', '-v', 'value', '-fs'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号