subprocess.Popen.stdout - reading stdout in real-time (again)

后端 未结 5 817
时光说笑
时光说笑 2020-12-09 19:12

Again, the same question.
The reason is - I still can\'t make it work after reading the following:

  • Real-time intercepting of stdout from another process in
5条回答
  •  一生所求
    2020-12-09 19:55

    Your particular example doesn't require "real-time" interaction. The following works:

    from subprocess import Popen, PIPE
    
    p = Popen(["./a.out"], stdin=PIPE, stdout=PIPE)
    output = p.communicate(b"12345")[0] # send input/read all output
    print output,
    

    where a.out is your example C program.

    In general, for a dialog-based interaction with a subprocess you could use pexpect module (or its analogs on Windows):

    import pexpect
    
    child = pexpect.spawn("./a.out")
    child.expect("input>>")
    child.sendline("12345.67890") # send a number
    child.expect(r"\d+\.\d+") # expect the number at the end
    print float(child.after) # assert that we can parse it
    child.close()
    

提交回复
热议问题