Search code examples
pythonenvironment-variableserrorlevel

How to read %ERRORLEVEL% enviroment variable in python


I need to read (and eventually change) %ERRORLEVEL% in my python script, but os.environ doesn't contain it. Is there a way to read it from somewhere else?


Solution

  • %ERRORLEVEL% gives us an understanding if a command which is executed in the CMD has successfully executed or not.

    Let's say, I have a python file

    import os
    elevel = os.system("cd")
    print(elevel)
    

    Here , the os.system("cd") will give the current directory path and elevel will be 0( 0 says no error while executing the command).

    and,

    import os
    elevel = os.system("c")
    print(elevel)
    

    Here, os.system("c") will give an output like 'c' is not an internal command. The elevel value will be 1 (1 denoting some error while executing the command)

    But, I am not sure if you can set the %errorlevel%. maybe you can throw an exception in python and which will make the error level to 1. Or similar way to make it one.

    Edit :

    from Difference between exit(0) and exit(1) in Python

    I found that we can give exit(1) , to exit python with an error implying %errorlevel% will be set to one in CMD.