pexpect モジュールを使用して、一連の質問をする perl スクリプトを実行する Python の次のコードがあります。私はこれをかなり長い間使用しており、今までうまく機能しています。
パイソンを期待する
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' <- 何らかの理由で 1 つにまとめられています
そこに何かアイデアはありますか?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";
}
}