In a bash script, use /dev/stdin for first of multiple command line inputs in wrapped script
Let's say I'm writing a bash script myscript.bash, which expects a single argument ($1). One of things it does is call wrapped.py, a python script, which prompts the user for four inputs. I want to submit $1 for the first of these inputs automatically, and then have the user prompted for the rest as normal.
How can I do this? I tried echo $1 | wrapped.py < /dev/stdin
, but this submits EOF for the second input requested by wrapped.py, causing a Python EOFError. It does work if I echo -e "$1\na\nb\nc", that is, echo all four inputs...but I want the user to be prompted for the other three. I could write a full-fledged wrapper for the Python script, but that creates maintenance issues, as an update to wrapped.py could e.g. add a fifth question.
Here's what the actual error looks like:
$ echo 'test_app' | django-startproject.py test_app tmp < /dev/stdin
Project name [PROJECT]: Project author [Lincoln Loop]: Traceback (most recent call last):
File "/usr/local/bin/django-startproject.py", line 7, in <module>
execfile(__file__)
File "/home/rich/src/ll-django-startproject/bin/django-startproject.py", line 9, in <module>
main()
File "/home/rich/src/ll-django-startproject/bin/django-startproject.py", line 5, in main
start_project()
File "/home/rich/src/ll-django-startproject/django_startproject/management.py", li开发者_运维百科ne 44, in start_project
value = raw_input(prompt) or default
EOFError: EOF when reading a line
The easy way:
(echo "$1"; cat) | rest of the pipe here
The disadvantage of this aproach is that the rest of the pipe sees the input as a pipe, and tends to lose most of the nice "interactive" properties. Then again, it depends on your script.
For anything more fancy, you should look into expect
.
You can set up things like this:
Your bash script
#!/bin/sh
./test.py $1
And python script
#!/usr/bin/python
import sys
print("In py script now")
for i in sys.argv:
print i
print raw_input('What day is it? ')
print raw_input('What date is it? ')
print raw_input('What month is it? ')
print ("Exiting py script")
And run like this
./myscript.bash abc
Output
In py script now
./test.py
abc
What day is it? 65
65
What date is it? 98
98
What month is it? 14
14
Exiting py script
精彩评论