打印生成的过程的输出会导致输出格式错误:为什么?

I'm trying to execute a python program from another python program using the pexpect library, but I don't get the behavior I was expecting.

I would like the output of the first program (prog1.py) to be displayed in real time on the terminal of the second program (prog2.py). Using child.after I get the output badly formatted: all \n and \r are printed in output instead of being correctly used as end of line.

child = pexpect.spawn('python3 /home/robb/Workspace/prog1.py')

child.expect(".*do:")
child.sendline(sys.argv[1])
print(child.after)

我将所有输出放在一行中:

b'Initializing database...\r\nDone initializing database!\r\n******************************\r\nProgram running\r\n******************************\r\n1. First Option\r\n2. Second Option\r\n\r\nPlease input number of action you want to do:'

Also, the answer to the question (the sys.argv[1], in this case) does not even appear. How to correctly display the output of prog1?

Using print(child.before) I get even a worse output, simply this:

b''
评论
  • 冷血动物
    冷血动物 回复

    The output is stored in child.after as a bytes object. To get an ASCII output, decode it accordingly:

    print(child.after.decode('ascii'))
    
    Initializing database...
    Done initializing database!
    ******************************
    Program running
    ******************************
    1. First Option
    2. Second Option
    
    Please input number of action you want to do:
    
    
  • zex
    zex 回复

    child.after returns you a bytes type instead of str that you would expect.

    Convert the output into str

    print(child.after.decode('utf8'))