how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

Related

How to replace error with a value in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I am using AutoSklearn library
in this library, there is a function called leaderboard()
sometimes this function gives error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/my/anaconda3/lib/python3.8/site-packages/autosklearn/estimators.py", line 841, in leaderboard
model_runs[model_id]['ensemble_weight'] = weight
KeyError: 1
I am using this function as part of a string
out = out + "automl.leaderboard() : " + automl.leaderboard() + "\n\r"
I want to replace the error with a string value "Error"
how can I do that?
P.S.
Here is the bug description for the error from the library github.
https://github.com/automl/auto-sklearn/issues/1441
You can use a try / except block. Something like this:
try:
out = out + "automl.leaderboard() : " + automl.leaderboard() + "\n\r"
except KeyError as err:
out = out + "automl.leaderboard() : " + str(err) + "\n\r"
Use try/except to try to get the leaderboard value, substituting "Error" when KeyError is raised:
try:
leaderboard = automl.leaderboard()
except KeyError:
leaderboard = "Error"
out += f"automl.leaderboard() : {leaderboard}\n\r"
You can use a try/except block to do this.
try:
leaderboard = automl.leaderboard()
except KeyError:
leaderboard = "Error" # If there is an error, leaderboard will be set to "Error"
out = out + "automl.leaderboard() : " + leaderboard + "\n\r"

IndentationError: expected an indented block within nested for loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am not sure where my indentation error is with my code. I am getting this error:
File "ex1.py", line 43
if v == 'arista_eos':
^
IndentationError: expected an indented block
Here is the code that is giving me the error:
for line in devices:
for k, v in line.items():
if v == 'juniper_junos':
try:
net_conn = ConnectHandler(**line)
config = net_conn.send_command("show config | display set")
filename = net_conn.host + '_' + time
with open(filename, mode='w') as f:
cwd = os.getcwd()
cfl = cwd + '/' + filename
f.write(config)
shutil.move(cfl, direct)
except NoValidConnectionsError:
if v == 'arista_eos':
try:
net_conn = ConnectHandler(**line)
config = net_conn.send_command("show run")
filename = net_conn.host + '_' + time
with open(filename, mode='w') as f:
cwd = os.getcwd()
cfl = cwd + '/' + filename
f.write(config)
shutil.move(cfl, direct)
except (NetMikoTimeoutException, NoValidConnectionsError, NameError):
except NoValidConnectionsError:
if v == 'arista_eos':
After except NoValidConnectionsError: there must follow an indented block which specifies what should happen in case of a NoValidConnectionsError:
except NoValidConnectionsError:
# indented block here
if v == 'arista_eos':
You omitted that for some reason, which isn't valid.

Python comparing two same string returns with false [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'll put some of my code bellow to explain the issue, but basically what I'm trying to do it to compare within a function - a string & a line that will include only that string.
I have the list as follows:
org_tasks = ['general_static ', 'host_general_static ',etc....]
which I'm passing to function with a filename (python file)
my_dict = createDictFromTaskList(ref_ver, org_tasks)
def createDictFromTaskList(prm_fl,tasks_list):
final_dict = {}
for task in tasks_list:
print getTransformedDic(prm_fl, str('CurrentTaskParams.' + task))
return final_dict
which calls:
def getTransformedDic(prm_fl,dic_name): # transforms string to dictionary
"turns dictionary values from type variable into a string"
newDic = ""
dicToChange = getOldDicAsString(prm_fl,dic_name)
if dicToChange is None: return None
dicToChange = dicToChange[len(dic_name) + 3:] #here i get none for some reason
dicToChange = dicToChange.replace('"', "'")
for line in dicToChange.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
if transformedLine.startswith('#'): continue
IsLineBelongsToDic = transformedLine.split(':')
if len(IsLineBelongsToDic) > 1:
if transformedLine[-1:] == ",":
valueAsString = '"%s",' % transformedLine[len(IsLineBelongsToDic[0]) + 1:-1]
else:
valueAsString = '"%s",' % transformedLine[len(IsLineBelongsToDic[0]) + 1:]
line = ' ' + IsLineBelongsToDic[0] + ' : ' + valueAsString
newDic += '%s' % line + '\n'
try:
value = ast.literal_eval(newDic[:-1])
except SyntaxError:
return None
else:
return value
def getOldDicAsString(prm_fl, dic_name):
"return a string that contains dictionary"
with open(prm_fl) as f:
file_data = f.read()
recordLines = False
dictionary = ""
for line in file_data.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
taskName = transformedLine.split('=')[0]
print taskName ,dic_name # here i can see they are the same
if taskName == dic_name or recordLines:
recordLines = True
dictionary += line + '\n'
if transformedLine == "}":
return dictionary
the file i work with looks as follows (according to list I've mentioned before):
...
CurrentTaskParams.general_static = {
'is_enable' : 'true'
}
CurrentTaskParams.host_general_static = {
'is_enable' : 'true'
}
...
after adding few prints I've seen that when for example I compare
CurrentTaskParams.general_static
--> which was passed as parameter
to the line containing this string (after striping in from spaces & '{' & '=' )
I dont append the dictionary string (meaning my 'if' returns false)
any help would be great,
thanks!
The following minimal example replicates your source data and your code block:
file_data = """
CurrentTaskParams.general_static = {
'is_enable' : 'true'
}
CurrentTaskParams.host_general_static = {
'is_enable' : 'true'
}
"""
dic_name = 'CurrentTaskParams.general_static'
for line in file_data.splitlines():
transformedLine = ''.join(line.split())
transformedLine = transformedLine.strip()
taskName = transformedLine.split('=')[0]
print("'%s'" % taskName, "'%s'" % dic_name, taskName == dic_name)
Running this it correctly picks up the line in question:
'' 'CurrentTaskParams.general_static' False
'CurrentTaskParams.general_static' 'CurrentTaskParams.general_static' True
''is_enable':'true'' 'CurrentTaskParams.general_static' False
'}' 'CurrentTaskParams.general_static' False
'CurrentTaskParams.host_general_static' 'CurrentTaskParams.general_static' False
''is_enable':'true'' 'CurrentTaskParams.general_static' False
'}' 'CurrentTaskParams.general_static' False
With a working example it is difficult to debug the problem(!) but I suspect this means the problem is somewhere else.
In your example code you list the org tasks with the trailing space still in place, is this intentional?
org_tasks = ['general_static ', 'host_general_static ',etc....]
I would suggest you try printing the data you believe to be matching but wrapped in quotes (see above) as this will help better highlight any leading/trailing spaces in your strings.

"NameError: name is not defined" for user input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am new to python and made a short script to try them out, while doing so I came across and error I've never had for the particular situation before, when I try to define uN as a str inputted by the user I get:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/classTest/classTest1.py", line 14, in <module>
uN = input(str("Username"))
File "<string>", line 1, in <module>
NameError: name 'ben' is not defined
The code is as follows:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = input(str("Username"))
pW = input(str("Password"))
usr1 = user(uN, pW)
usr1.createUsrPw()
I have used the x = input(str()) syntax a lot before and never had this error, and the error traces back to line 1, so is uN = input(str("Username")) still being considered a part of the class?
when I simplify the code to this it works perfectly:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(usrName)
f.write(" ")
f.write(pWord)
f.write("\n")
f.close()
usr1 = user("Ben", "testPw")
usr1.createUsrPw()
with the file usrName.txt being appended to include "Ben testPw" as intended.
You should use raw_input instead of input as you are using Python 2.X. input works in Python 3.
This code would work:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = raw_input("Username")
pW = raw_input("Password")
usr1 = user(uN, pW)
usr1.createUsrPw()
Use raw_input. This looks like a Python 2 error, I don't think you're using Python 3
You also don't need to call str on a string literal. str("asdf") == "asdf"

while true loop in python can't be stopped [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with this loop in python:
i = 1
while True:
with open('/tmp/file.txt', 'r+') as f:
for line in f:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
result = Function()
if "statement" in result:
out = open('/tmp/result.txt', 'a+')
out.write(result)
out.close()
i = i + 10
else:
return i
I want first read file.txt line by line and then for each line count i till statement exists in result but this loop is infinitive... So I removed break and used return i instead. but no result
How can I tell the while True loop to be stopped when all lines from file.txt is read and for each line counter is completed?
UPDATE
what I want to process:
word1line1word2line1counter=1test
word1line1word2line1counter=2test
word1line1word2line1counter=3test
.
.
.
#`till my if condition is true` then
word1line2word2line2counter=1test
word1line2word2line2counter=2test
word1line2word2line2counter=3test
.
.
.
and so on
Thanks
I think you need to switch your loops around:
i = 1
with open('/tmp/file.txt', 'r+') as f:
for line in f:
result = ...
while "statement" in result:
with open('/tmp/result.txt', 'a+') as out:
out.write(result)
i += 10
result = ...
Although it is not at all clear what this algorithm is supposed to be doing
I found the answer:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
for line in f:
i = 1
line=line.strip('\r\n ')
while True:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
print work
result = Function()
if "statement" in result:
out.write(result)
i += 10
else:
break
out.close()

Categories