How to replace error with a value in python [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 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"

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [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 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.

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.

time conversion from Unix timestamp to ISO timestamp [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
so here is my code:
import psycopg2
import datetime
conn = psycopg2.connect(database="sample", user="postgres", password="", host="localhost", port="5432")
cur = conn.cursor()
print "Opened database successfully"
ii=0
with open ('sms-call-internet-tn-2013-11-01.txt') as f:
for line in f:
print line;
arr= line.split('\t');
square_id=[0];
time_interval=datetime.datetime.utcfromtimestamp(int(arr[1]).strftime('%Y-%m-%d %H:%M:%S'));
country_id=index[2];
smsin=arr[3];
if arr[3]==" ":
arr[3]="0"
smsout=arr[4];
if arr[4]==" ":
arr[4]="0"
callin=arr[5];
if arr[5]==" ":
arr[5]="0"
callout=arr[6];
if arr[6]==" ":
arr[6]="0"
internet=arr[7]
if arr[7]==" ":
arr[7]="0"
cur.execute ("INSERT INTO tn2013_12_02 VALUES (" + square_id + ", " + time_interval + ", " + country_id + ", " + smsin + ", " + smsout + ", '" + callin + "', "+ callout +", "+ internet +")");
conn.commit()
ii= ii+1;
This is the error:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
AttributeError: 'long' object has no attribute 'strftime'
You have misplaced parentheses. Change this:
datetime.datetime.utcfromtimestamp(int(arr[1]).strftime('%Y-%m-%d %H:%M:%S'))
to this:
datetime.datetime.utcfromtimestamp(int(arr[1])).strftime('%Y-%m-%d %H:%M:%S')

"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"

Print lines read from file on same line [duplicate]

This question already has answers here:
Print new output on same line [duplicate]
(7 answers)
Closed 7 years ago.
I've tried many different things to achieve this, simply I want this:
import requests
path1 = 'D:\test\Files\/results.txt'
lines1 = open(path1).readlines()
ctr = 0
for i in lines1:
try:
r = requests.get(i)
if r.status_code != 200:
ctr += 1
print(i, " Status Code: ", r.status_code)
except requests.ConnectionError:
ctr += 1
print(i, " Failed to connect")
print("Counter", ctr)
to output like this:
URL Status Code: xyz
But instead I'm getting:
URL
Status Code: xyz
So, what's the best way to print out something in the same line with Python?
i is a line. Just strip it to remove any possible newline at the end, before printing it:
print(i.rstrip(), " Status Code: ", r.status_code)

Categories