从shell中向Python脚本提供输入?

3

我想编写一个shell脚本,用于运行一个需要接收原始输入的python文件。该python脚本大致如下:

def main():
    name=raw_input("What's your name?")
    print "Hello, "+name
main()

我希望shell脚本能够运行脚本并自动输入。我看到很多获取shell输入的方法,如从python函数返回值中获取,或者如何通过python运行带有输入的shell脚本,但没有这样的方法。基本上,我只是想要一个这样的东西:
python hello.py
#  give the python script some input here
#  then continue on with the shell script.

3
我们到底在谈论哪种shell?请翻译这段内容:echo "read this!" | python hello.py - moooeeeep
那看起来像是一个 UUOE(与 UUOC 密切相关) - mgilson
还可以查看这篇关于Python自动化测试和标准输入的回答 - moooeeeep
2个回答

8

你是指像这样的吗:

python hello.py <<EOF
Matt
EOF

这被称为 bash HERE document

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"

第二个是无用的 cat 用法... python hello.py < john.txt - mgilson
@mgilson 事实上...旧习惯难改。 - Fredrick Brennan
我仍然经常这样做。 - mgilson
我实际上不能更改Python文件:我正在为一门入门计算机科学课程打分,他们没有教sys。我只是试图节省时间,这样我就不必手动输入94个学生的Python脚本。 - kip_price

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接