如何读取sys.exit()返回的值并将其存储在变量中

时间:2015-12-09 09:19:05

标签: python perl exit-code

我最后有一个sys.exit(0)sys.exit(-1)的python脚本(0或1取决于是否发生了错误)。如何将0或1存储在变量中?例如,在环境变量或perl脚本使用的变量中

2 个答案:

答案 0 :(得分:1)

如果在普通shell中运行python代码,则会得到$?变量:

   $ python yourscript.py
   $ echo $?  # this will echo the sys.exit value

这在perl脚本中也有效:

 system("python yourscript.py");

 if ($? == -1) {
        print "failed to execute: $!\n";
    }
    elsif ($? & 127) {
        printf "child died with signal %d, %s coredump\n",
        ($? & 127),  ($? & 128) ? 'with' : 'without';
    }
    else {
        printf "child exited with value %d\n", $? >> 8;
    }

答案 1 :(得分:1)

如果您在Windows中使用%ERRORLEVEL%

CMDPROMPT>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.exit(-1)
CMDPROMPT>echo %ERRORLEVEL%
-1
CMDPROMPT>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]     on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.exit(0)
CMDPROMPT>echo %ERRORLEVEL%
0
CMDPROMPT>