python stdin和期望

问题描述

我想让程序与python脚本对话,我有以下代码

spawn "python3" "python.py" 
expect -re "(.*)\r\n"
set command_output $expect_out(1,string)
puts "the result is ($command_output)"
expect -re "(.*)"
send "sss\n"
send "aaa\n"
expect -re "(.*)\r\n"
set command_output $expect_out(1,string)      # my problem. is in the matched string here
puts "the second result is ($command_output)"

在匹配的字符串中,我发送的数据(sss和aaa)也匹配了,我不想要

python代码

import sys


print(' "hello" mmm uart')


data = sys.stdin.readline()
data2 = sys.stdin.readline()

if data == "sss\n":
    print(str(len(data)))
else:
    print("not sss")

我尝试使用sys.stdin.flush()sys.stdout.flush()不能解决我的问题,我尝试添加一个额外的expect *来清除同样无法解决expect_out(1,string)

你能帮我吗

解决方法

这不是您真正需要的东西。在Expect / tcl中,您可以写

set command_output [exec python3 python.py << "sss\naaa\n"]
set output_lines [split $command_output \n]
puts "the first result is ([lindex $output_lines 0])"
puts "the second result is ([lindex $output_lines 1])"

如果您真的很想使用期望,那么问题在于,您可以用作expect模式的内容很少。您可以这样做:

spawn python3 python.py
send "sss\r"
send "aaa\r"
expect eof
set output_lines [split $expect_out(buffer) \n]
puts "the first result is ([string trim [lindex $output_lines 0]])"
puts "the second result is ([string trim [lindex $output_lines 3]])"

最后一条命令中的列表索引为3,因为发送的两行显示在缓冲区中。