Search code examples
pythonperlexit-code

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


I have a python script with sys.exit(0) or sys.exit(-1) in the end (0 or 1 depending on whether an error has occurred). How do I store this 0 or 1 in a variable? For example, in an environment variable or in a variable used by a perl script


Solution

  • If you run your python code in a normal shell you have the $? variable:

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

    This is also valid inside your perl script:

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