How to get exit code from Python? - python

I have a python code. I use cmd file to execute my python code. In the cmd file, I am going to get errorlevel from my python code.
infile = "FeatureByte.txt"
Array = ["6J", "yB", "ss", "11"]
with open(infile, "r") as input_file:
output_list = []
for rec in input_file.read().splitlines():
rec = rec[:-3]
FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)]
output_list.append(FBlist)
print(output_list)
FBlist_set = set(FBlist)
Array_set = set (Array)
if Array_set & FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
This is my cmd file :
set logfile=C:\Users\Log.txt
set PYTHONPATH="C:\Users\AppData\Local\Programs\Python\Python37-32"
set PYTHONEXE="%PYTHONPATH%\Python -B"
"C:\Users\AppData\Local\Programs\Python\Python37-32\python.exe" -B C:\Users\Desktop\Pyth.py
echo %ERRORLEVEL% >> "%logfile%"
From these both code, I always get 1 inside my Log.txt file.

I think the problem is in this line:
if Array_set & FBlist_set:
print ("Found")
exit(0)
Change it to:
if Array_set and FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
& that you use is bitwise operator and not the logical operator and. Because of which the if condition fails and you get to the else part which returns exit(1) to you as status code.

The noticed return of 0 and 1 as commented response to roganjosh and Devanshu Misra's solution is because your If-statement is written to do so due to a indentation typo (perhaps lacking an IDE editor?).
You have:
if Array_set & FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1)
This code always exits with "1". In some cases it exits first with "0" but followed with "1".
It should be:
if Array_set and FBlist_set:
print ("Found")
exit(0)
else:
print ("Not Found")
exit(1) # <--- this exit(1) should be inside the "else" clause.
No need here to point out the use of "&" instead of "and" as this was addressed earlier by roganjosh. Anyway, keep an eye on the changed color of "and". Its blue and means that it became a selection participant in the if-statement.
... but watch out for the result FBlist = [''] because it will trigger a false positive FBlist_set and thus exit the wrong way.
Enjoy ;-)

Related

Return string from Python to Shell script

I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.

Python switching the display based on input using If, Else

I want to display print text based on my Input value using IF/Else or Switch. And Also let me know how to use switch case for below code.
# OnButtonOK after clicking it, display the input value
def OnButtonOK(self):
Input = self.entrytext.get()
# self.text.insert(END, Input + '\n')
# self.scroll.config(Input = self.text.yview)
print Input
useroption = atoi(Input)
# self.OnButtonClick();
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
return;
def SubMenu1(self):
print 'SubMenu1'
return;
def SubMenu2(self):
print 'SubMenu2'
return;
def SubMenu3(self):
print 'SubMenu3'
return;
I am able to print only else part:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
Let me know where exactly i am going wrong.
I think you have indentation problems in your code:
Python use 4 spaces(you can use 1 space but 4 is good practice) indentation language. Means if/else statement will be like this:
if a == 1:
print("A = 1") # 4 spaces w.r.t to above statement
elif a == 2:
print("A = 2")
elif a ==3:
print("A = 4")
else:
print("A = pta nahi")
you can use above if/else statements as a switch case and also your indentation problem will be solved
It's a simple beginner's mistake, you're indenting it worng:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
should be
if (useroption == 1):
print "input is output" # You had an indent too many here
self.SubMenu1();
else:
print "Error:Invalid"
Python is indentation sensitive; too many or too few indentations will break your code.

Python Basic if statements

Hi Guys for the below code i want to execute only if the first condition satisfy so please help me
print('welcome')
username = input()
if(username == "kevin"):
print("Welcome"+username)
else:
print("bye")
password = input()
if(password == "asdfg"):
print("Acess Granted")
else:
print("You Are not Kevin")
If I got this right, you want to exit/terminate the script at the "else" block of the 1st if statement.
There are two approaches - 1st is that you use sys.exit():
import sys
#if statement here
...
else:
print("bye")
sys.exit()
2nd is that you put your 2nd if under the 1st if's else block:
...
else:
password = input()
if password=="abcdef":
#do something here
else:
print("you're not Kevin")
Also, I see that you're using brackets after the if statements (if (condition):). That is not necessary for Python 3.x as far as I'm concerned.
See: https://repl.it/CEl7/0

else statement keep looping print 'not found' in python [duplicate]

This question already has answers here:
print if else statement on python
(2 answers)
Closed 8 years ago.
I want to print not found ONCE if in the text file not found a string. But the string keeps printing not found following how many line in the file. Its because it read all the line. So it printing all not found based on how many lines in it. Is there other way to do it?
import os
f = open('D:/Workspace/snacks.txt', "r");
class line:
for line in f.readlines():
if line.find('chocolate') != -1:
print "found ", line
elif line.find('milkshake') != -1:
print "found ", line
else:
print "not found"
Are you looking for the break statement in python? As the name reflects, this statement simply breaks you out of the loop.
Eg:
for line in f.readlines():
if line.find('chocolate') != -1:
print "found ", line
elif line.find('milkshake') != -1:
print "found ", line
else:
print "not found"
break
First, remove this line - class line:. Re-indent the lines below it.
Two things should help you:
break clause
else clause in for loop
Please read the official tutorial on control flow.
And then the code becomes like this
>>> for line in f.readlines():
... if line.find('chocolate') != -1 or line.find('milkshake') != -1:
... print "found ", line
... break
... else:
... print "not found"
...
not found

Program not printing the expected exception

I am working on a program that will extract a text from a file like so:
NAME OF PROGRAM: text.txt
CONTENTS OF FILE:
1: 101010100101010101 1010010101010101 101010101010101
2: 0101010101 1010011010 10101010 10101010 10101010
3: 0001000101010 10101010 10101010 1010101010 10101
START LINE: 1
END LINE: 2
results.txt generated.
I am at the part where the program will ask for the name of the program and I plan to use exceptions when the name of the program has the length of zero.
The program should have ran like:
NAME OF PROGRAM:
THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN 1! [LEN_ERROR]
But the program run like so:
NAME OF PROGRAM:
THERE'S SOMETHING WRONG WITH YOUR INPUT! [INP_ERROR]
Here's the code:
class Program:
"""
Author : Alexander B. Falgui (alexbfalgui.github.io)
Program Name : Text Extractor
Description : Takes an integer or string as an input and generates a
text file with the extracted data.
Note: This program can be used, shared, modified by anyone.
"""
def __init__(self):
self.menu_file_loc = "menu"
return self.load_files()
def load_files(self):
#self.menu_file = open(self.menu_file_loc)
#self.read_mf = self.menu_file.read()
return self.main_menu()
def main_menu(self):
#print(self.read_mf)
print(""" [1] Extract Data\n [2] Exit""")
while (True):
try:
self.menu_input = input("CHOOSE AN OPTION> ")
if (self.menu_input == 1):
try:
self.program_name = raw_input("\nNAME OF THE PROGRAM: ")
self.program_name = open(self.program_name)
except IOError:
if (len(program_name) == 0):
print("THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN"),
print(" 1! [LEN_ERROR]")
print("%s does not exist" % self.program_name)
elif (self.menu_input == 0):
print("\n")
break
except SyntaxError:
continue
except NameError:
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
# Run the program
Program()
Why did the program print the wrong exception and what can I do to fix that?
Please don't do except SyntaxError: continue, because you will silently go over any kind of syntax error.
To get more information about what's going wrong, you should except NameError as e to investigate further. See also https://docs.python.org/2/tutorial/errors.html
You should change the except NameError-part to the following:
except NameError as e:
print e
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
and you will see what really goes wrong.
I'm not sure why you added those two exception handler at the end but you are getting a Name Exception because your refer to the program_name variable instead of self.program_name
Change your line if (len(program_name) == 0): to if (len(self.program_name) == 0): and it should work.

Categories

Resources