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.
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 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.
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 years ago.
Improve this question
Hi I want to run make for loop to run infinitely.
for eg.
while True:
try:
script()
except Exception as e:
script()
continue
as below because in For loop I have lists where i want to apply on scripts which run in sequencing and continuous
while True:
try:
for symbol in symbol:
script()
except Exception as e:
for symbol in symbol:
script()
continue
I guess you are trying to run a program even when there is an exception and break at some condition, you do not want to run the loop infinitely I suppose. you can do
While true:
try:
for symbol in symbols:
script(symbol) ' you should break however somewhere
Exception as e:
continue
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')
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
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