【问题标题】:Interact with standard input/output of another process与另一个进程的标准输入/输出交互
【发布时间】:2015-03-15 11:52:26
【问题描述】:

我有一个可执行文件example.exe。该可执行文件的行为如下:

1.Waits for input from user
2.Performs some operations, based on input
3.goto 1

如何使用subprocess 或类似模块与可执行文件进行交互?

我希望运行该流程,插入输入,接收输出,然后根据收到的输出插入额外的输入。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:
    from subprocess import Popen, PIPE
    
    process = Popen([r'path/to/process', 'arg1', 'arg2', 'arg3'], stdin=PIPE, stdout=PIPE)
    
    to_program = "something to send to the program's stdin"
    while process.poll() == None:  # While not terminated
        process.stdin.write(to_program)
    
        from_program = process.stdout.readline()  # Modify as needed to read custom amount of output
        if from_program == "something":  # send something new based on stdout
           to_program = "new thing to send to program"
        else:
           to_program = "other new thing to send to program"
    
    print("Process exited with code {}".format(process.poll()))
    

    【讨论】:

    • 第一次调用stdout后,stderr = process.communicate(to_program)进程终止...(所有额外的输入被认为是空字符串)
    • communicate() 方法读取所有输出并等待子进程退出后再返回。
    • 对不起,应该测试得更彻底。试试这个新的例子。
    • 1-一般来说,你不知道应该读多少和there are other issues with the interactive subprocess usage 2-这里不需要调用process.poll(),调用process.poll()是不够的- - 进程可能在.poll() 调用之后但在.write() 调用之前退出(无关:使用is None 而不是== None)。您应该处理由.write() 引发的IOError 错误(EPIPEEINVAL)。如果from_program 为空,则表示EOF,您可以退出循环。
    • 3-次要:关闭管道并在最后调用process.wait()
    猜你喜欢
    • 2017-02-03
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2010-11-23
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多