Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
dumb_ass_questions Avatar asked Feb 27 '26 07:02

dumb_ass_questions


2 Answers

It's working fine for me if you set a System Variable and reference it with

os.environ["VARIABLE_NAME"]

See below:

enter image description here

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'
>>>
like image 132
AK47 Avatar answered Mar 01 '26 21:03

AK47


%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.

like image 37
Vijayanathan jayaprakash Avatar answered Mar 01 '26 21:03

Vijayanathan jayaprakash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!