3

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?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • Do you understand the percent-signs are not part of the var name? They are cmd.exe syntax for substituting the value of the var name between the percent signs. In a UNIX shell, like bash, the equivalent is `echo $ERRORLEVEL`. So in a program you should use `ERRORLEVEL`. – Kurtis Rader Oct 24 '19 at 21:04
  • @KurtisRader thanks for the info, i didnt know that. But in my program i've been using ```ERRORLEVEL``` and it didnt work. – retardquestions Oct 25 '19 at 12:33

2 Answers2

3

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'
>>>
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • ERRORLEVEL is an existing variable in my system (windows). I can read it using the command line for example, but python somehow doesnt see it. – retardquestions Oct 24 '19 at 13:05
1

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