从Perl调用Python脚本

时间:2018-07-09 20:16:04

标签: python perl

我试图在perl中捕获一个python exit coode形式。

我的python代码py_test.py:

import sys
sys.exit(sys.argv[1])

我的perl代码test.pl:

#!/usr/bin/perl -w
$res = system("python py_test.py ".$ARGV[0]);
print("\$res ==== $res \n >>>". $? ."\n");

我跑了

perl test.pl 4

结果是:

4
$res ==== 256
>>>256

我在32位RHEL 5.3上使用python 2.4.3和perl 5.8.8。

有人可以帮助我了解这里发生的事情吗,我似乎无法理解这种行为,我做错了什么吗? (我看了几个小时的代码,从未遇到过系统怪异的东西)

2 个答案:

答案 0 :(得分:1)

我发现了问题。 我输入sys.exit argv [1],但是在开始时python将其视为字符串。 将其更改为sys.exit(int(argv [1]))后,一切正常。

这也解释了为什么打印“ 4” ...

答案 1 :(得分:0)

来自“ perldoc perlvar”

$?      The status returned by the last pipe close, backtick (``) command,
        successful call to "wait()" or "waitpid()", or from the "system()"
        operator. This is just the 16-bit status word returned by the
        traditional Unix "wait()" system call (or else is made up to look
        like it). Thus, the exit value of the subprocess is really ("$? >>
        8"), and "$? & 127" gives which signal, if any, the process died
        from, and "$? & 128" reports whether there was a core dump.

听起来您的python脚本可能无法成功退出4。

test.py

#!/usr/bin/env python3

import sys

sys.exit(4)

test.pl

#!/usr/bin/env perl
use warnings;
use strict;

system("./test.py");
print "\$? = $?\n"
die("Killed by signal ".( $? & 0x7F ) if $? & 0x7F;
die("Exited with error ".( $? >> 8 ) if $? >> 8;
print "Success\n";

结果:

~/test$ ./test.pl
$? = 1024
Exited with error 4