python - 在 Python 中通过管道传输到 raw_input()

标签 python raw-input piping

我怎样才能让程序执行目标程序,然后将文本输入到它的标准输入(例如 raw_input。)

例如,像这样的目标程序:

text = raw_input("What is the text?")
if text == "a":
    print "Correct"
else:
    print "Not correct text"

最佳答案

你期待什么样的答案?

是的,你可以。但是你也会把一些东西放在 stdout 上,如果它在管道中使用就不需要了。此外,您必须像遍历 sys.stdin 一样遍历 raw_input 以逐行获取输入:

while True:
    text = raw_input("What is the text?")
    if text == "a":
        print "Correct"
    elif text == "stop":
        print "Bye"
        break
    else:
        print "Not correct text"

但如 Zen of Python – PEP20 中所述,“应该有一个——最好只有一个——显而易见的方法来做到这一点。”在你的情况下,那就是使用sys.stdin

(编辑):因为我可能没有正确理解 OP 的要求,要从 python 程序中运行另一个程序,您需要使用 subprocess.Popen()

import subprocess

text = "This is the text"

data = subprocess.Popen(['python', 'other_script.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate(input=text)
print data[0]

关于python - 在 Python 中通过管道传输到 raw_input(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394477/

相关文章:

python - 关于树状图的一些问题 - python (Scipy)

bash - 为什么管道输入到 "read"仅在馈入 "while read ..."构造时才有效?

Python:使用 YAML 自动创建类方法

Python用线性插值正则化不规则时间序列

python - 了解 Python 中的 raw_input 函数

Python 通过写入 stdin 取消 raw_input/input?

c++ - 使用原始输入同时获取两只老鼠的数据

python - 为什么 Python 的子进程的管道输出如此不可靠?

php - 将邮件通过管道传输到 PHP 时提取附件

python - 如何根据停止标准对排序的 DataFrame 进行分组?