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')
Related
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}")
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
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.
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
Trying to write a code that exits on a pressing CTRL + C anywhere in the code had problems implementing because most of online help refer to signalling and other stuff
this might not be related to what am asking for. Can skip this part and provide a solution
import signal
import time
def sigint_handler(signum, frame):
print 'Stop pressing the CTRL+C!'
signal.signal(signal.SIGINT, sigint_handler)
Objective:
Pressing ctrl + c should just quit the program
You can either do a try/except on a KeyboardInterrupt:
try:
while True:
print 1
except KeyboardInterrupt:
print "test"
Alternatively, if the process itself is killed, you will get a SIGTERM sent by the KILL command:
As you indicated, you can define a handler: signal.signal(signal.SIGTERM, my_signal_term_handler)
Here are a list of all the UNIX signals to consider : http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals. Note that SIGKILL cannot be caught.
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