【问题标题】:How to make a Python program handle a here document?如何让 Python 程序处理此处的文档?
【发布时间】:2011-03-25 17:16:09
【问题描述】:

我编写了一个 Python 包装器 (pyprog) 来运行一个程序 (someprogram),如下所示:

...do some setup stuff in Python...
print("run [y=yes]")
CHOICE=input()
...do some setup stuff in Python...
if CHOICE == "y":
  status=subprocess.call(["someprogram"])
  sys.exit(status)

用户想要使用 shell 脚本来运行程序并使用如下文档提供输入:

#!/bin/sh
pyprog > pyprog.log << EOF
y
file1
file2
EOF

有没有办法生成子进程,以便此处的文档可以工作(“y”被 Python input() 消耗,“file1”和“file2”继续作为标准输入到某个程序)?现在,Python input() 接受了“y”,但其余部分消失了。

【问题讨论】:

  • 这里的“工作”是什么意思?您当前的解决方案到底有什么不适合的?
  • 您是否尝试将此处的文档传递到子流程中?
  • 是的,我正在尝试将此处的文档传递到子流程中。现在,整个事情都终止了,因为“someprogram”没有得到输入“file1”和“file2”。
  • Arg...好吧,我刚刚意识到我在我的 Python 脚本中做了一些影响这一点的事情(我没有提到它)。 Python 脚本中有一个查询,它搞砸了 - 将编辑原始问题。

标签: python shell subprocess


【解决方案1】:

您需要将sys.stdin 连接到呼叫的stdin

status=subprocess.call(["someprogram"], stdin=sys.stdin)

【讨论】:

    【解决方案2】:
    import sys
    status=subprocess.call(["someprogram"], stdin=sys.stdin)
    

    【讨论】:

      【解决方案3】:

      我以前用过几次这样的东西:https://gist.github.com/887225

      基本上它是一个 python 脚本,它接受一些命令行参数,根据输入的内容执行一些转换,然后使用 os.system() 来调用 shell 命令。 在这个例子中,我调用 Java,传入一个类路径,然后运行 ​​ProgramName.jar 程序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-23
        • 2011-03-28
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多