Code:
def funt():
print(Fore.GREEN, end='')
tool = input('Enter Desired Tool: ')
if tool == 'web':
try:
print(Fore.CYAN, end='')
site = input('Please Enter The Website Here: ')
response = requests.get(site)
requests.get(site)
if response.status_code == 200:
print(f'{Fore.GREEN}Online!')
sleep(1)
else:
print(f'{Fore.RED}Offline!')
sleep(1)
while True:
funt()
Location of Error is while True: .
The Error Is As Follows:
while True:
^
IndentationError: unexpected unindent
I cannot find a solution, there is not any sign of indentation in the while loop.
try expects an except block followed by it.
You can modify your code as follows:
def funt():
print(Fore.GREEN, end='')
tool = input('Enter Desired Tool: ')
if tool == 'web':
try:
print(Fore.CYAN, end='')
site = input('Please Enter The Website Here: ')
response = requests.get(site)
requests.get(site)
if response.status_code == 200:
print(f'{Fore.GREEN}Online!')
sleep(1)
else:
print(f'{Fore.RED}Offline!')
sleep(1)
except:
pass
while True:
funt()
But writing proper code requires you to handle exceptions. So, if possible write a piece of code in the except block.
You've missed except block for your try block
Here's some info on exception handling in python.
Do this:
def funt():
print(Fore.GREEN, end='')
tool = input('Enter Desired Tool: ')
if tool == 'web':
try:
print(Fore.CYAN, end='')
site = input('Please Enter The Website Here: ')
response = requests.get(site)
requests.get(site)
if response.status_code == 200:
print(f'{Fore.GREEN}Online!')
sleep(1)
else:
print(f'{Fore.RED}Offline!')
sleep(1)
# You were missing this part:
except:
print("Message")
while True:
funt()
A try block always goes together with a catch block. The purpose of the try block is to attempt to run code that may throw an exception. The catch block is what catches this exception.
Related
The code I have works. The last for loop gets reached and choice.click() gets clicked on. The question I have is why the except block gets executed even though the:
if choice.text == call_resource:
choice.click()
break
piece of the code is reached and the choice.click() portion works?
def select_choice(driver, resource_tag):
try:
call_resource = None
access_data = common.retrieve_tag_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
if call_resource is None:
access_data = common.retrieve_fixture_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
menu = driver.find_element_by_css_selector("ul[role='listgrid']")
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
except:
error(logger, "unable to select choice")
pass
Because the last for loop works, shouldn't it break entirely out of the function after choice.click() without executing the except: portion of the code?
The except: portion will run only if an Exception occurred inside the try block. You should change the except: line to something like except Exception as e: and print the variable e in some way so you can discover what the problem is.
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
Could be replaced with since your only trying to click one element with a certain text why not just try to find it. If it errors out it will go to the exception you provided.
driver.find_element(By.XPATH,f"//li[#role='choices' and contains(text(),{call_resource})]").click()
Also use to find errors use the following.
except Exception as e:
print(str(e))
Reddit Bot Question: I'm trying to see if any comment has the phrase "Hello There." in it and if it doesn't have "Hello There." in it, I want it to print "Nothing Found." once and wait until a comment is found. It works like a charm but instead of printing "Nothing Found." once and waiting for another comment, it prints "Nothing Found." repeatedly for an infinite amount of time until a comment comes. I've tried multiple options and ways from multiple forums but I can't seem to get this correct. Here is the code:
def run_bot():
while True:
for comment in r.subreddit("test").comments(limit=10):
comment_text = comment.body.lower()
isMatch = any(string in comment_text for string in words_match)
if comment.id not in cache and isMatch and comment.author != r.user.me():
comment.reply("[GENERAL KENOBI!](https://youtu.be/rEq1Z0bjdwc)\n\n^(*I am a bot, and this action was performed automatically.*)")
print(comment.id)
cache.append(comment.id)
with open("commentcache.txt", "a") as f:
f.write(comment.id + "\n")
print("Resetting in:")
def countdown(n):
while n > 0:
print (n, "...")
n = n - 1
time.sleep(1)
if n ==0:
print("Reset Successful!")
time.sleep(1)
countdown(5)
else:
print("Nothing Found.")
def saved():
if not os.path.isfile("commentcache.txt"):
commentcache = []
else:
with open("commentcache.txt", "r") as f:
commentcache = f.read
commentcache = commentcache().split("\n")
commentcache = list(filter(None, commentcache))
return commentcache
cache = saved()
print(cache)
run_bot()
The trouble starts at:
else:
print("Nothing Found.")
it prints that infinitely.
The easiest way is probably a boolean flag:
print_status = True
while True:
...
if isMatch and ...:
comment.reply("[GENERAL KENOBI!] ...")
...
print_status = True
elif print_status:
print("Nothing found")
print_status = False
I'm trying to write a program for an assignment that uses urllib3 to download a webpage and store it in a dictionary. (I'm using spyder 3.6)
The program is giving me an 'AttributeError' and I have no idea what I'm doing wrong. here is my code with step by step notes I wrote for the assignment.
#Downloading a webpage
import urllib3
import sys
#these import statements allow us to use 'modules' aka 'libraries' ....
#code written by others that we can use
urlToRead = 'http://www.google.com'
#This value won't actually get used, because of the way the while loop
#below is set up. But while loops often need a dummy value like this to
#work right the first time
crawledWebLinks = {}
#Initialize an empty dictionary, in which (key, value) pairs will correspond to (short, url) eg
#("Goolge" , "http://www.google.com")
#Ok, there is a while loop coming up
#Here ends the set up
while urlToRead != ' ':
#This is a condition that dictates that the while loop will keep checking
#as long as this condition is true the loop will continue, if false it will stop
try:
urlToRead = input("Please enter the next URL to crawl")
#the "try" prevents the program from crashing if there is an error
#if there is an error the program will be sent to the except block
if urlToRead == '':
print ("OK, exiting loop")
break
#if the user leaves the input blank it will break out of the loop
shortName = input("Please enter a short name for the URL " + urlToRead)
webFile = urllib3.urlopen(urlToRead).read()
#This line above uses a ready a readymade function in the urllib3 module to
#do something super - cool:
#IT takes a url, goes to the website for the url, downloads the
#contents (which are in the form of HTML) and returns them to be
#stored in a string variable (here called webFile)
crawledWebLinks[shortName] = webFile
#this line above place a key value pair (shortname, HTML for that url)
#in the dictionary
except:
#this bit of code - the indented lines following 'except:' will be
#excecuted if the code in the try block (the indented following lines
#the 'try:' above) throw and error
#this is an example of something known as exeption-handling
print ("*************\nUnexpected Error*****", sys.exc_info()[0])
#The snip 'sys.exc_info()[0]' return information about the last
#error that occurred -
#this code is made available through the sys library that we imported above
#Quite Magical :)
stopOrProceed = input("Hmm..stop or proceed? Enter 1 to stop, enter anything else to continue")
if stopOrProceed ==1 :
print ('OK...Stopping\n')
break
#this break will break out of the nearest loop - in this case,
#the while loop
else:
print ("Cool! Let's continue\n")
continue
# this continue will skip out of the current iteration of this
#loop and move to the next i.e. the loop will reset to the start
print (crawledWebLinks.keys())
Your issue is that you are trying to call urllib3.urlopen(), and urllib3 does not have a member urlopen Here is a working snippet. All that I did was replace urllib3 with urllib.request:
import urllib.request
import sys
urlToRead = 'http://www.google.com'
crawledWebLinks = {}
while urlToRead != ' ':
try:
urlToRead = input("Please enter the next URL to crawl: ")
if urlToRead == '':
print ("OK, exiting loop")
break
#if the user leaves the input blank it will break out of the loop
shortName = input("Please enter a short name for the URL " + urlToRead + ": ")
webFile = urllib.request.urlopen(urlToRead).read()
crawledWebLinks[shortName] = webFile
except:
print ("*************\nUnexpected Error*****", sys.exc_info()[0])
stopOrProceed = input("Hmm..stop or proceed? Enter 1 to stop, enter anything else to continue")
if stopOrProceed ==1 :
print ('OK...Stopping\n')
break
else:
print ("Cool! Let's continue\n")
continue
print (crawledWebLinks)
Another note, simply printing out the type of error in your except block is not very useful. I was able to debug your code in 30 seconds once I removed that and viewed the actual traceback.
I'm trying to get input from user, until he press ctrl-c. yet, I can't catch the
error, I think it has something to do with sklearn (I imported it for the rest of the code)
this is the code:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")`
Fix your indentation as the following:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")
In my code below, it stops executing when I hit an exception. How can I get it to re-enter the try statement from where the exception left off? Maybe I am looking for a different way to tackle this without a try-except statement?
import requests
from requests import exceptions
contains_analyst = []
try:
for x in data:
r = requests.get(str(x), timeout=10, verify=False)
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst # %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
You should put the try/except around only the part whose error you want to trap. In your example, it looks like you want something more like this:
for x in data:
try:
r = requests.get(str(x), timeout=10, verify=False)
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
else:
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst # %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
Here I use the else clause of the try block to handle the case where no exception is raised (see documentation). In many cases, if you don't need to do anything else after the exception, you could just return at that point and put the following no-exception code in the main function body, reducing indentation a bit:
for x in data:
try:
r = requests.get(str(x), timeout=10, verify=False)
except exceptions.RequestException:
contains_analyst.append("COULD NOT CONNECT")
return contains_analyst
# execution reaches here if no exception
if "analyst" in r.text:
contains_analyst.append("Analyst")
print "Analyst # %s" % x
else:
contains_analyst.append("NOPERS")
print "Nopers"
Of course, whether it makes sense to return at that point depends on the surrounding context of your code.