如何从shell向Python脚本输入数据?
我正在尝试写一个shell脚本,这个脚本会运行一个需要一些原始输入的python文件。这个python脚本大致是这样的:
def main():
name=raw_input("What's your name?")
print "Hello, "+name
main()
我希望这个shell脚本能够运行这个python脚本,并自动给它输入。我见过很多方法可以从python函数返回的结果中获取shell输入,或者如何从python运行shell并提供输入,但我没有找到反过来的方法。基本上,我只是想要一个能做到以下操作的东西:
python hello.py
# give the python script some input here
# then continue on with the shell script.
2 个回答
4
其实,没有比 sys.stdin
更好的方法来获取原始输入了。它在不同的平台上都能使用。
import sys
print "Hello {0}!".format(sys.stdin.read())
然后
echo "John" | python hello.py # From the shell
python hello.py < john.txt # From a file, maybe containing "John"
8