There is a faster way to use googlemaps API 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 2 months ago.
Improve this question
Im currently using python to georefernce a dataset of 10512 observations, but is way slow using this code
gmaps = googlemaps.Client(key='APIKEYXXXXXXXXXXXXXXXXXXXXXX')
BD2021['lat']=0
BD2021['lon']=0
for i in range(len(BD2021)):
try:
geocode_result = gmaps.geocode(BD2021['DIRECCION'][i]+',Barranquilla, Colombia')
BD2021['lat'][i]=geocode_result[0]['geometry']['location']['lat']
BD2021['lon'][i]=geocode_result[0]['geometry']['location']['lng']
except:
try:
geocode_result = gmaps.geocode(BD2021['RAZON_SOCIAL'][i]+',Barranquilla, Colombia')
BD2021['lat'][i]=geocode_result[0]['geometry']['location']['lat']
BD2021['lon'][i]=geocode_result[0]['geometry']['location']['lng']
except:
pass
Theres is any faster way that you can recommend, that script have been loading for 30 mins and I dont know even its doing a good job.

Without knowing at all what BD2021 is in more detail, it's hard to definitively help, but a variation like this has more robust error handling, and also a cache, so if the same address happens to be multiple times in your dataset, the program will only geocode it once per run. (You could use a package like diskcache for a more persistent cache.)
from functools import cache
# ...
gmaps = googlemaps.Client(key="APIKEYXXXXXXXXXXXXXXXXXXXXXX")
#cache
def get_geocode(address):
return gmaps.geocode(address)
BD2021["lat"] = {}
BD2021["lon"] = {}
for i in range(len(BD2021)):
for possible_address in (
BD2021["DIRECCION"][i] + ",Barranquilla, Colombia",
BD2021["RAZON_SOCIAL"][i] + ",Barranquilla, Colombia",
):
try:
geocode = get_geocode(possible_address)
if geocode and geocode[0]:
BD2021["lat"][i] = geocode[0]["geometry"]["location"]["lat"]
BD2021["lon"][i] = geocode[0]["geometry"]["location"]["lng"]
break
except Exception as e:
print(f"Error processing {possible_address}: {e}")
else:
print(f"Could not find geocode for index {i}")

Related

simple mqtt script 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 yesterday.
Improve this question
My code is working well as expected but i would like to improve it. When a loop enter in a big time sleep like 100s how can i force it to change imediatly. if i miss input and put 400s and not 4s i would have to restart the program it's anoying. Here you can see the code
I tried many things like making other variable etc but i'm new and quiet lost.
`import paho.mqtt.client
import time
import threading
monClientMqtt = paho.mqtt.client.Client()
monClientMqtt.connect("localhost",1883)
monClientMqtt.loop_start()
monClientMqtt.subscribe("option")
monClientMqtt.subscribe("periodeX")
monClientMqtt.subscribe("mesureX")
monClientMqtt.subscribe("periodeY")
monClientMqtt.subscribe("mesureY")
monClientMqtt.subscribe("valeurX")
monClientMqtt.subscribe("valeurY")
periodeX =1
mesureX=0
x=0
y=0
periodeY=1
mesureY=0
def CallBack (client, userdata,message) :
global x,periodeX,mesureX,y, periodeY,mesureY
print(message.topic)
print(message.payload)
if message.topic == "option" :
if message.payload.decode() == "restartX" :
x=0
if message.payload.decode()=="restartY":
y=0
if message.topic =="mesureX":
try:
mesureX=float(message.payload.decode())
except ValueError:
print("0 ou 1")
if message.topic =="periodeX" :
try:
periodeX=float(message.payload.decode())
except ValueError :
print("Veuillez entrer un nombre")
if message.topic =="mesureY":
try:
mesureY=float(message.payload.decode())
except ValueError:
print("0 ou 1")
if message.topic =="periodeY" :
try:
periodeY=float(message.payload.decode())
except ValueError :
print("Veuillez entrer un nombre")
def prendremesureX():
while True:
if mesureX==0:
global x,periodeX
x+=1
monClientMqtt.publish("valeurX",x)
time.sleep(periodeX)
def prendremesureY():
while True :
if mesureY==0:
global y,periodeY
y+=1
monClientMqtt.publish("valeurY",y)
time.sleep(periodeY)
threadX=threading.Thread(target=prendremesureX)
threadY=threading.Thread(target=prendremesureY)
monClientMqtt.on_message=CallBack
threadX.start()
threadY.start()
Please see the other comments directing you on how to properly ask questions/how to use stack overflow.
Question issues aside, if I am understanding your question correctly, you are asking; "How can I adjust the delay of my checks, in case there is an emergent need?"
The problem with your current implementation, is that you are using time.sleep(), which is functionally suspending any processing until the time frame expires. This won't work, as you have discovered, since no changes can be made mid-sleep.
What you are looking to do, is to create a task scheduler. You would want to assign a date or time to a specific task, and have a task handler that would do processing of each task, depending on the particular time.
Subsequently, if something needs to be urgently processed, you would update the scheduled time of the task, to be processed as needed.

Somebody help me understand this ctypes python code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
hotkey_ = enable_shortcut # Check to break the while loop
def proper_fctn():
if hotkey_:
if not user32.RegisterHotKey(None, shortcut_id, modifier, vk):
pass
try:
msg = wintypes.MSG()
while user32.GetMessageA(byref(msg), None, 0, 0) != 0:
if msg.message == win32con.WM_HOTKEY:
if not hotkey_:
break
fctn_to_run()
user32.TranslateMessage(byref(msg))
user32.DispatchMessageA(byref(msg))
except:
pass
If somebody could help me understand the lines, so I could understand the process better.
These are Win32 APIs. All of them are well-documented in Microsoft's MSDN documentation. You've basically written a Windows application with a standard main loop.
Google takes you straight to their docs.
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage

Close Only One Chrome Tab on TaskBar [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have 2 chrome tabs like that:
Tabs
I want to close one of them.I will use python to close.How can I close?
Using psutil module this can be achieved
Given code will kill first instance of process found. (If you want to kill all instance you can remove/comment return statement inside try block)
import psutil
def kill_process_by_name(processName):
# Iterate over all running processes
for proc in psutil.process_iter():
# Get process detail as dictionary
pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
# Check if process name contains the given name string.
try:
if processName.lower() in pinfo['name'].lower():
print(pinfo)
p = psutil.Process(pinfo['pid'])
p.terminate()
return
except Exception as e:
pass
#ignore any exception
return
kill_process_by_name( processName='chrome')

Python - Undo script if script fails [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Sometimes when I run a function in my python script and if the function gives me an output which is not desired, I need to undo this step and then try running the function again with different parameters. Is there a way that I can have the script undo what it has done if my function gives me a wrong output.For only one set of parameters, the desired output is acheived.
PS: By running the function means making permanent changes.
Example:
def function():
for i in range(parameters):
value = perform_operation(parameters[i]) #makes permanent changes
if value != some_value:
undo(perform_operation())
You need to create another function than cleans what was done in the main function for example (delete newly created files, remove installed packages, etc ...) and use it.
def main_func():
proc = subprocess.Popen('touch test test2')
return proc.returncode
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
result = main_func()
if main_func() != 0 :
clean_main_func()
or you can raise an error then catch it:
def main_func():
proc = subprocess.Popen('touch test test2')
if proc.returncode !=0 :
raise Error
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
try:
result = main_func()
except Error:
clean_main_func()
It's juste an example , and hope it answer your question.

Doing something after for loop finishes in same function? [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 8 years ago.
Improve this question
Is this possible? I'm doing an bukkit plugin now (in Python, yes :D), and I'm forced to do this within one function, so I can't separate it and call it later... For example, if I have loop that loops through players on server and adds everyone except one player, I want it to finish, and then teleport i.e. "Player1" to random player. At the moment, it teleports "Player1" to random player every time because of for loop... I'll give you just little of code, since It looks messy in preview due to many things that are not involved in problem and could be confusable to you... Here it is:
listica = []
for p1 in org.bukkit.Bukkit.getWorld(nextvalue).getPlayers():
if p1.getName() not in listica:
try:
listica.remove(event.getPlayer().getName())
randomtarget = choice(listica)
randomtargetreal = org.bukkit.Bukkit.getPlayer(randomtarget)
event.getPlayer().teleport(randomtargetreal)
event.getPlayer().sendMessage("%sYou teleported to: %s%s"% (bukkit.ChatColor.GREEN, bukkit.ChatColor.DARK_GREEN, randomtarget))
except ValueError:
randomtarget = choice(listica)
randomtargetreal = org.bukkit.Bukkit.getPlayer(randomtarget)
if event.getPlayer().getLocation() != randomtargetreal.getLocation():
event.getPlayer().teleport(randomtargetreal)
event.getPlayer().sendMessage("%sYou teleported to: %s%s"%(bukkit.ChatColor.GREEN, bukkit.ChatColor.DARK_GREEN, randomtarget))
What I want is:
run for loop:
when there is no more players to add a.k.a it finishes
do try loop
P.S. I can't do it in separate function.
Thanks in advance! :)
Do you mean:
def func(args):
for item in loop:
do something
try: # note indentation
something else

Categories