生成的进程的打印输出导致格式错误的输出:为什么?
Printing output of a spawned process results in a badly formatted output: why?
我正在尝试使用 pexpect
库从另一个 python 程序执行一个 python 程序,但我没有得到预期的行为。
我希望第一个程序 (prog1.py
) 的输出实时显示在第二个程序 (prog2.py
) 的终端上。使用 child.after
我得到的输出格式错误:所有 \n
和 \r
都打印在输出中而不是被正确用作行尾。
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:'
此外,问题的答案(在本例中为 sys.argv[1]
)甚至没有出现。
如何正确显示prog1
?
的输出
使用 print(child.before)
我得到更差的输出,就是这样:
b''
child.after
returns 你是 bytes
类型而不是你期望的 str
。
将输出转换为str
print(child.after.decode('utf8'))
输出作为 bytes
对象存储在 child.after
中。要获得 ASCII 输出,请相应地对其进行解码:
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:
我正在尝试使用 pexpect
库从另一个 python 程序执行一个 python 程序,但我没有得到预期的行为。
我希望第一个程序 (prog1.py
) 的输出实时显示在第二个程序 (prog2.py
) 的终端上。使用 child.after
我得到的输出格式错误:所有 \n
和 \r
都打印在输出中而不是被正确用作行尾。
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:'
此外,问题的答案(在本例中为 sys.argv[1]
)甚至没有出现。
如何正确显示prog1
?
使用 print(child.before)
我得到更差的输出,就是这样:
b''
child.after
returns 你是 bytes
类型而不是你期望的 str
。
将输出转换为str
print(child.after.decode('utf8'))
输出作为 bytes
对象存储在 child.after
中。要获得 ASCII 输出,请相应地对其进行解码:
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: