我在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'< - INCORRECT
问题3:'回答2answer 2'< - 由于某种原因将其合并为一个
有什么想法吗?在产生我的pexpect对象时,我没有使用任何特殊的东西:child=pexpect.spawn(cmd,timeout=140)
编辑:添加了询问问题2&的perl代码函数。 3
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;
}
}
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";
}
}
答案 0 :(得分:0)
你的python方面的代码没有任何问题。检查代码的perl端。为了演示我在下面创建了一个python问题和答案相互调用的脚本。当您执行answers.py
时,它将产生如下预期输出。此外,您不需要执行sleep语句,child.expect将阻塞,直到收到预期的输出。
<强> questions.py 强>
answers = {}
for i in range(1, 4):
answers[i] = raw_input('Question %s:' % i)
print 'resuls:'
print answers
<强> answers.py 强>
import pexpect
child=pexpect.spawn('./questions.py', timeout=140)
for i in range(1, 4):
index = child.expect('Question %s:' % i)
child.sendline('answer%s' % i)
child.expect('resuls:')
print child.read()
<强>输出强>
{1: 'answer1', 2: 'answer2', 3: 'answer3'}