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?
It's working fine for me if you set a System Variable and reference it with
os.environ["VARIABLE_NAME"]
See below:

Inside the terminal:
C:\Users\ak47>echo %ERRORLEVEL%
true
C:\Users\ak47>python
Python 2.7.16 (v2.7.16:413a49145e, Mar 4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ["ERRORLEVEL"]
'true'
>>>
%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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With