我在 Python 中有以下代码,使用 pexpect 模块来运行 perl 脚本,该脚本会询问一系列问题。我已经使用了很长一段时间,并且直到现在都运行良好。
期待蟒蛇
index = child.expect(['Question 1:'])
os.system('sleep 2')
print 'Question 1:' + 'answer1'
child.sendline('answer1')
index = child.expect(['Question 2:'])
os.system('sleep 2')
print 'Question 1:' + 'answer2'
child.sendline('answer2')
index = child.expect(['Question 3:'])
os.system('sleep 2')
print 'Question 1:' + 'answer2'
child.sendline('answer2')
此时,我有一些代码可以检查问题 2 和问题 3 不匹配时是否会输出错误。我检查了 pexpect 日志,发送的语句正是我想要的(字节数和字符串数)。
但是,当我检查 perl 代码接受的内容时,它会得到以下信息:
问题 1:“答案 1”<-- 正确
问题 2:“答案 1”<-- 不正确
问题 3:'answer 2answer 2' <-- 由于某种原因它被合并为一个
有什么想法吗?生成我的 pexpect 对象时,我没有使用任何特殊的东西:child=pexpect.spawn(cmd,timeout=140)
编辑:添加了询问问题 2 和 3 的 perl 代码功能
子getpw
sub getpw
{ my ($name, $var, $encoding) = @_;
my $pw = $$var;
PWD: while(1) {
system("/bin/stty -echo");
getvar($name, \$pw, 1);
print "\n";
system("/bin/stty echo");
return if $pw eq $$var && length($pw) == 80;
if (length($pw) > 32) {
print STDERR "ERROR: Password cannot exceed 32 characters, please reenter.\n";
next PWD;
}
return if $pw eq $$var;
my $pw2;
system("/bin/stty -echo");
getvar("Repeat password", \$pw2, 1);
print "\n";
system("/bin/stty echo");
print "#1: ";
print $pw;
print "\n";
print "#2: ";
print $pw2;
if ($pw2 ne $pw) {
print STDERR "ERROR: Passwords do not match, please reenter.\n";
next PWD;
}
last;
}
# Escape dangerous shell characters
$pw =~ s/([ ;\*\|`&\$!#\(\)\[\]\{\}:'"])/\\$1/g;
my $correctlength=80;
my $encoded=`$AVTAR --quiet --encodepass=$pw`;
chomp($encoded);
if($? == 0 && length($encoded) == $correctlength) {
$$var = $encoded;
} else {
print "Warning: Password could not be encoded.\n";
$$var = $pw;
}
}
子getvar
sub getvar
{ my ($name, $var, $hide) = @_;
my $default = $$var;
while(1) {
if($default) {
$default = "*****" if $hide;
print "$name [$default]: ";
} else {
print "$name: ";
}
my $val = <STDIN>;
chomp $val;
### $val =~ s/ //g; # do not mess with the password
$$var = $val if $val;
last if $$var;
print "ERROR: You must enter a value\n";
}
}