如何从预期测试 mySQL 响应中解析整数?
How to Parse an integer out of an expect test mySQL response?
有谁知道我如何在 expect 测试中从以下控制台输出中解析整数?
+-----------------+
| static_route_id |
+-----------------+
| 314 |
+-----------------+
我想做的是
proc testRouteId { identity_regex } {
#sign into database (got it)
#fetch routes with matching identity_regex (a column in the database)
send { select static_route_id from static_routes where identity_regex="$identity_regex"; }
send "\r"
#parse the routeId out of the console output somehow
expect {
timeout { send_user "fetchStaticRouteId timed out\n"; return 0 }
eof { send_user "fetchStaticRouteId failed\n"; return 0 }
=========Stuck on the regex =========
-re "REGEX?" { send_user "fetchStaticRouteId $expect_out(1, string)\n" }
}
return routeId; # (an int)
}
使用expect
命令匹配正则表达式模式,捕获由竖线和空格包围的数字序列,并从expect_out
数组中提取数字。
在这里,我使用 Tcl format
命令(如 sprintf)使发送字符串更易于使用。您发送的命令将 不会 扩展变量,因为您使用了大括号——参见 https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm 规则编号 6。
send [format {select static_route_id from static_routes where identity_regex="%s";\r} $identity_regex]
expect -re {\|\s+(\d+)\s+\|.*}
return $expect_out(1,string)
这是解决方案
proc itemId { databaseName idRegex } {
set query = "select itemId from tableName where idRegex = '$idRegex';"
spawn -noecho mysql -uUSERNAME -pPASSWORD $databaseName -B -e "$query"
expect {
timeout {send_user "itemId timed out"; return 0 }
eof {send_user "itemId failed"; return 0}
"routeId" {
expect {
-re { *(\d+).*} { set itemId $expect_out(1,string) }
}
}
}
return $itemId
}
有谁知道我如何在 expect 测试中从以下控制台输出中解析整数?
+-----------------+
| static_route_id |
+-----------------+
| 314 |
+-----------------+
我想做的是
proc testRouteId { identity_regex } {
#sign into database (got it)
#fetch routes with matching identity_regex (a column in the database)
send { select static_route_id from static_routes where identity_regex="$identity_regex"; }
send "\r"
#parse the routeId out of the console output somehow
expect {
timeout { send_user "fetchStaticRouteId timed out\n"; return 0 }
eof { send_user "fetchStaticRouteId failed\n"; return 0 }
=========Stuck on the regex =========
-re "REGEX?" { send_user "fetchStaticRouteId $expect_out(1, string)\n" }
}
return routeId; # (an int)
}
使用expect
命令匹配正则表达式模式,捕获由竖线和空格包围的数字序列,并从expect_out
数组中提取数字。
在这里,我使用 Tcl format
命令(如 sprintf)使发送字符串更易于使用。您发送的命令将 不会 扩展变量,因为您使用了大括号——参见 https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm 规则编号 6。
send [format {select static_route_id from static_routes where identity_regex="%s";\r} $identity_regex]
expect -re {\|\s+(\d+)\s+\|.*}
return $expect_out(1,string)
这是解决方案
proc itemId { databaseName idRegex } {
set query = "select itemId from tableName where idRegex = '$idRegex';"
spawn -noecho mysql -uUSERNAME -pPASSWORD $databaseName -B -e "$query"
expect {
timeout {send_user "itemId timed out"; return 0 }
eof {send_user "itemId failed"; return 0}
"routeId" {
expect {
-re { *(\d+).*} { set itemId $expect_out(1,string) }
}
}
}
return $itemId
}