【问题标题】:Give input to a python script from a shell?从 shell 向 python 脚本提供输入?
【发布时间】:2013-02-19 18:59:59
【问题描述】:

我正在尝试编写一个 shell 脚本,该脚本将运行一个接受一些原始输入的 python 文件。 python脚本基本上是这样的:

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

我希望 shell 脚本运行脚本并自动向其中提供输入。我已经看到很多方法可以从 python 函数返回的内容中获取 shell 输入,或者如何使用输入从 python 运行 shell,但不是这样。基本上,我只想做一些事情:

python hello.py
#  give the python script some input here
#  then continue on with the shell script.

【问题讨论】:

  • echo "read this!" | python hello.py - 我们到底在说什么外壳?
  • 这看起来像一个UUOE(与UUOC密切相关)
  • 还可以查看this answer,了解 Python 中的自动化测试和标准输入。

标签: python shell


【解决方案1】:

你的意思是这样的:

python hello.py <<EOF
Matt
EOF

这被称为bash HERE document

【讨论】:

    【解决方案2】:

    没有比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"
    

    【讨论】:

    • 第二个是没用的猫……python hello.py &lt; john.txt
    • @mgilson 确实......旧习惯很难改掉。
    • 我仍然这样做(相当频繁)。
    • 我实际上无法更改 python 文件:我正在为 CS 入门课程评分,他们不教 sys。我只是想节省自己的时间,所以我不会手动输入 94 名学生的 Python 脚本。
    相关资源