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

how to read the value returned by sys.exit() and store it in a variable

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

如果您 运行 您的 python 代码在正常 shell 中,您有 $? 变量:

   $ 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;
    }

如果您在 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>