module googlesearch returns same result multiple times - python

when i run my code, the output returns the same result multiple times, when i need to to return different results every time. how would i fix this?
count = 0
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
def Gsearch(searchQuery): #global count fixed counter, result is still returning the same thing
global current_time
global count
count += 1
try :
import googlesearch
for i in googlesearch.search(query=searchQuery,tld="com",lang="en",num=10,stop=10,pause=2):
print ("(" + current_time + ")")
print (count)
print(i + "\n")
gs = Gsearch(searchQuery)
gs.Gsearch()
except ImportError:
print("No module named 'google' found. To install, type 'pip install google' into cmd.")
I have tried to change the 'num' and 'stop' functions, have tried using 'break', and enumerate. Nothing works that I have tried, I have looked everywhere online yet have found almost no info on my specific problem, I have looked at the PyPi page of the module yet there is no information on it. Any tips much appreciated.

Dont call gs = Gsearch(searchQuery) and gs.Gsearch() in the function def Gsearch(searchQuery). It makes infinite recursion and won't stop. This recursion makes the search query results always equal by taking the very first result in each call of the function. Just try this :
from datetime import datetime
import googlesearch
from time import sleep
global current_time
global count
def Gsearch(searchQuery): #global count fixed counter, result is not returning the same thing
try :
count = 0
for i in googlesearch.search(query=searchQuery,tld="com",lang="en",num=10,stop=10,pause=2):
current_time = datetime.now().strftime("%H:%M:%S")
print ("(" + current_time + ")")
print (count)
print(i + "\n")
count += 1
sleep(1)
# gs = Gsearch(searchQuery)
# gs.Gsearch()
except ImportError:
print("No module named 'google' found. To install, type 'pip install google' into cmd.")
Gsearch('your query')

Related

Insert separator in Python input() function

I'm looking for a way to insert separator in the input() function.
To be clear, my script asks the user to input a timeout in H:MM:SS, and I'd like Python to insert : by himself.
So if the user types "14250", I want the terminal to display 1:42:50 (during the input, not after pressing ENTER).
Is it possible in Python?
Here's a version for Linux. It is based on and very similar to the version by anurag, but Linux's getch modules does not know getwch and putwch, so those have to be substituted.
from getch import getche as getc
def gettime():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ', end='', flush=True)
for i in range(6):
timestr += getc() # get and echo character
if i in (1, 3): # add ":" after 2nd and 4th digit
print(":", end="", flush=True)
timestr += ':'
print() # complete the line
return timestr
time = gettime()
print("The time is", time)
Sample output:
Enter time in 24-hr format (hh:mm:ss): 12:34:56
The time is 12:34:56
I think this would also work on Windows with from msvcrt import getwche as getc but I can not test this.
There is a way to achieve the result (to some extent), tested on Windows 10, Python 3.7:
import msvcrt as osch
def main():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ', end='', flush=True)
for i in range(6):
ch = osch.getwch()
if i!=0 and i%2==0:
osch.putwch(':')
timestr += ':'
osch.putwch(ch)
timestr += ch
return timestr
if __name__ == "__main__":
res = main()
print('\n')
print(res)
Please note that the variable timestr was created merely as storage for future use. Also, you can apply all kinds of validity checks. In my opinion, this method can't be used to parse a time input of type 14923 into 1:49:23 as lookahead is not available and there is no way of knowing whether user is going to input 12-hr time or 24-hr time. I am going for 24-hr time, which means, instead of 14923, user will be required to enter 014923.

How to make try function in PYTHON execute only once while except executes many times?

How can I make my script print "number" only once if the "try" goes right and doesn't show errors?
When it goes wrong, I want it to keep trying and printing ("Error. Attempt: " + str(x)). But if it goes right I want it to print (number) only once.
This script was made in order to track when a certain excel spreadsheet is created in the folder. When it is in the folder, I want the script to print (number).
The issue is when the excel is already in the folder, the script keeps printing (number) 16 times, until num_retries is done.
num_retries = 16
interval = 2
for x in range(1, num_retries):
try:
result = open("I:/workbook.xls")
import xlrd
workbook = xlrd.open_workbook("I:/workbook.xls")
worksheet = workbook.sheet_by_name("sheet1")
number = worksheet.cell(3, 13).value
print(number)
except:
sleep(interval)
print("Error. Attempt: " + str(x))
pass
Thanks!
Add break after your print(number) so when it gets the right number if jumps out of the loop. Your code would be like this:
for x in range(1, num_retries):
try:
result = open("I:/workbook.xls")
import xlrd
workbook = xlrd.open_workbook("I:/workbook.xls")
worksheet = workbook.sheet_by_name("sheet1")
number = worksheet.cell(3, 13).value
print(number)
break
except:
sleep(interval)
print("Error. Attempt: " + str(x))
pass

Downloading a webpage using urllib3

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.

Python3x Unbound Local Error

I have reviewed the answers to similar questions and have tried various recommended iterations but am not having any luck. I am getting this error "UnboundLocalError: local variable 'rundate1' referenced before assignment" on the line "return pick.CalendarFrame(rundate1)". My code is
def GetCalendar():
os.system("Pick.py")
def rundate1():
result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?")
#result = tkinter.messagebox.askyesno()
if result == True:
rundate1 = date.today() - timedelta(7)
print("rundate 1 = ", rundate1)
return rundate1
else:
GetCalendar()
return pick.CalendarFrame(rundate1)
print("rundate 1 = ", rundate1)
return rundate1
rundate = rundate1()
print("rundate = ", rundate)
The first part of the if statement works fine, I click yes and get the return data. When "no" is clicked my calendar dialog pops up and I can pick my dates but then it all falls apart. The app "Pick.py" works great on it's own. The submit for the CalendarFrame is
def submit():
start = self.result1.strftime("%m/%d/%Y")
end = self.result2.strftime("%m/%d/%Y")
rundate1 = start, end
return rundate1
print(rundate1)
Help would be very nuch appreciated

Progress dots with a Thread in Python

I am trying to create a thread in Python that will poll some server as long as it won't get proper answer (HTTP GET). In order to provide convenient text UI I want to print progress dots. Another dot with every connection attempt until it finish (or just another dot with every another second of waiting).
I have found something like this: http://code.activestate.com/recipes/535141-console-progress-dots-using-threads-and-a-context-/
In this example we have context manager:
with Ticker("A test"):
time.sleep(10)
I am not sure if I understand that properly. I would like to do something like:
with Ticker("A test: "):
result = -1
while result != 0:
result = poll_server()
print "Finished."
But this does not work. Any ideas?
Cheers
Python buffers your output, so many dots will appear at once. One way around that is to import sys and use that: whenever you want to print a dot, say:
sys.stdout.write(".")
sys.stdout.flush()
The flush makes the dot appear immediately.
#! /usr/bin/python3
import sys
import time
def progress(message):
i = 0
while True:
dots = ""
i = (i % 3) + 1
dots += "." * i + " " * (3 - i)
sys.stdout.write("\r{}".format(message + dots))
sys.stdout.flush()
i += 1
time.sleep(0.3)
if __name__ == "__main__":
progress("Waiting")
More useful example:
#! /usr/bin/python3
import sys
import time
def progress_gen(message):
i = 0
while True:
for x in range(0, 4):
dots = "." * x
sys.stdout.write("{}\r".format(message + dots))
i += 1
time.sleep(0.5)
sys.stdout.write("\033[K")
yield
if __name__ == "__main__":
p = progress_gen("Waiting")
for x in range(1, 100):
next(p)
if x == 3:
break
print("Finished")
You can test it online: https://repl.it/#binbrayer/DotsProgress

Categories