【问题标题】:In Python how to pipe a string into an executables stdin?在 Python 中,如何将字符串通过管道传输到可执行文件标准输入中?
【发布时间】:2012-07-19 06:16:08
【问题描述】:

在 Windows 上,我有一个从标准输入读取的程序 (prog.exe)。在 python 中,我想通过管道将字符串作为其标准输入的输入。该怎么做?

类似:

subprocess.check_output("echo {0} | myprog.exe".format(mystring)) 

或(使 args 成为列表)

subprocess.check_output("echo {0} | myprog.exe".format(mystring).split())

似乎不起作用。它给了我:

WindowsError: [Error 2] The system cannot find the file specified

我还尝试将“stdin”关键字 arg 与 StringIO(这是一个类似文件的对象)一起使用

subprocess.check_output(["myprog.exe"], stdin=StringIO(mystring))

仍然没有运气 - check_output 不适用于 StringIO。

【问题讨论】:

  • 请注意,wim 的答案绝对是这里的方法,但是,如果您在 check_output 调用中使用 shell=True,您的尝试可能会奏效。

标签: python windows subprocess pipe


【解决方案1】:

您应该使用 Popen communicate 方法 (docs)。

proc = subprocess.Popen(["myprog.exe"], stdin=subprocess.PIPE)
stdout, stderr = proc.communicate('my input')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2014-02-22
    • 1970-01-01
    • 2023-03-23
    • 2022-07-05
    相关资源
    最近更新 更多