python windows: exit a loop when cmd window closes - python

I run the following code in a cmd window. Many different exceptions may occur within the try loop, this is why I generalize to except all exceptions. But: If I close the cmd window the code runs in, how do I stop the code from keep running even though the cmd window is closed.
while True:
try:
print('test') # in actual code more complicateed task with many possible exceptions
except Exception:
pass
Right now, I can only quit this code via a restart.
EDIT: I tried to catch the exception but the log file only says "log works"
import sys
from time import sleep
import logging
logging.basicConfig(filename="logtest.log",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %
(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("log works")
while True:
try:
print('test')
sleep(1)
except Exception as e:
logging.info(e)
logging.info(str(e))

This is because in your try statement you need to set a condition where the execution breaks for example below:
x = 0
while True:
try:
if (x == 10):
break
else:
# in actual code more complicated task with many possible exceptions
print('test')
x += 1
except Exception as e:
print(e.printStackTrace())
Another method can be using a keyword to force break out of the while loop for example below we are using q to end the loop execution:
'''
from time import sleep
import re
input_text= ""
while True:
try:
# in actual code more complicateed task with many possible exceptions
input_text = input("Enter your selection .....")
print(input_text)
if re.search('q' , input_text , re.IGNORECASE):
break
except Exception as e:
print(e.printStackTrace())
'''

Well, your script never received any exception, it was just killed without any possibility to log anything.
We are not in the Unix world where a shell just kindly telss its child that it is exiting with a SIGHUP signal letting them know where they want to die or not. We are in a MS/DOS inheritance: when a console ends, every process attached to the console dies.
So unless you have detached the process from its console it is over. You can easily control it with Windows task manager (start it with Ctrl Alt Del)

Related

how to avoid a python script to hangs until both user uses ctrl+C & keep it possible

Was given a script I would reuse more or less, I need to be able to to both :
end the execution by itself
capture ctrl-c to exit on user action
I saw many clues to the second part on other answers/question of stackoverflow similar to :
try:
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
pass
In my point of view I should run the execution functions (main) in
while mycondition:
try:
mainfunction()
except KeyboardInterrupt:
personalised_exit()
Why not (if I undersoud well as I am still a python noob), but why not a more declarative code with usage of signal modules ?
something might look then like
import signal
import sys
def signal_handler(sig, frame):
[...]
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
main()
signal.pause()

Python misinterpret KeyboardInterrupt exception when using Lingoes

I want to write a python program (run.py) that always runs and only stops running when Ctr-C is pressed. This is how I implement it:
wrapper.py:
import subprocess
import signal
def sig_handler(signum, frame):
res = input("Ctrl-c was pressed. Do you really want to exit? y/n ")
if res == 'y':
exit(1)
signal.signal(signal.SIGINT, sig_handler)
while(True):
p = None
p = subprocess.Popen("python run.py", shell=True)
stdout, stderr = p.communicate()
run.py:
print('aaaaa')
print('bbbbb')
However, when I hold left-mouse and select text in the terminal that is running wrapper.py, this event is understood incorrectly as Ctr-C then the wrapper.py stop running run.py. My question is how to prevent reading mouse events as KeyboardInterrupt in python (Unix). Thanks!
Terminal
Instead of using a module like signal to achieve this you could opt to use exceptions since it is a pretty exceptional case that your program will receive a keyboard interrupt.
#!/usr/bin/env python3
import sys
def main() -> int:
try:
while True:
print(sys.argv)
except KeyboardInterrupt as e:
return 0
if __name__ == '__main__':
try:
sys.exit(main())
except Exception as e:
print(f'Error: {e}', file=sys.stderr)
sys.exit(1)
The source code has no problem. The problem is caused by dictionary software. The software has a feature of selecting word to translate. By somehow it converts the mouse event (selecting word) to Ctr-C then the program above exits. When I turn off the dictionary software, the problem disappears. I will close the thread here

Python- How to check if program gets aborted by user while running?

If I am running a python program on linux terminal and i abort it manually by pressing ctrl+c, how can i make my program do something when this event occurs.
something like:
if sys.exit():
print "you chose to end the program"
You can write a signal handling function
import signal,sys
def signal_handling(signum,frame):
print "you chose to end the program"
sys.exit()
signal.signal(signal.SIGINT,signal_handling)
while True:
pass
pressing Ctrl+c sends a SIGINT interrupt which would output:
you chose to end the program
Well, you can use KeyBoardInterrupt, using a try-except block:
try:
# some code here
except KeyboardInterrupt:
print "You exited
Try the following in your command line:
import time
try:
while True:
time.sleep(1)
print "Hello"
except KeyboardInterrupt:
print "No more Hellos"
Check the KeyboardInterrupt exception in Python.
You can put your code in a try block, catch the KeyboardInterrupt exception with except and let the user know that he has exited.

When cancelling a Python script do something [duplicate]

This question already has answers here:
How do I capture SIGINT in Python?
(12 answers)
Closed 9 years ago.
When i press CTRL+C to cancel a running python script, is there a way to run a certain python code before the script terminates?
Use try/except to capture for KeyboardInterrupt, which is raised when you press CTRL+C.
Here is a basic script to demonstrate:
try:
# Main code
while True:
print 'hi!'
except KeyboardInterrupt:
# Cleanup/exiting code
print 'done!'
This will continually print 'hi!' until you press CTRL+C. Then, it prints 'done!' and exits.
CTRL+C raises KeyboardInterrupt. You can catch it just like any other exception:
try:
main()
except KeyboardInterrupt:
cleanup()
If you really don't like that, you can also use atexit.register to register cleanup actions to run (provided that you don't do something really nasty and cause the interpreter to exit in a funky way)
try:
# something
except KeyboardInterrupt:
# your code after ctrl+c
I'm pretty sure you just need a try/finally block.
Try out this script:
import time
def main():
try:
while True:
print("blah blah")
time.sleep(5)
except KeyboardInterrupt:
print("caught CTRL-C")
finally:
print("do cleanup")
if __name__ == '__main__':
main()
Output should be something like:
blah blah
caught CTRL-C
do cleanup
This code
import time
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
print "Any clean"
gives
deck#crunch ~/tmp $ python test.py
^CAny clean
when I press Ctrl+C when executing.
You just have to handle KeyboardInterrupt exception.
Also you can deal with signals to set handlers.

Python: signal.pause() equivalent on Windows

I have my main application thread that spawns 2 threads and I catch SIGINT in my main thread to quit them nicely.
On linux, I'm using signal.pause() and it works perfectly.
What is the best way to implement signal.pause() on Windows?
My ugly solution is:
my_queue.get(True, averylongtime)
And put something in my_queue in my signal handler. Note that if I don't specify a timeout, SIGINT is not caught. But I wonder if there's a better solution.
Thank you
I use this:
#another:
while not self.quit:
# your code
# main
try:
# your code
except KeyboardInterrupt:
another.quit = True
time.sleep(5) # or wait for threading.enumerate() or similar
If I want it more robust, say, exit in presence of bugs too:
except KeyboardInterrupt:
another.quit = True
signal.alarm(5)
time.sleep(6)
A side effect to this is that every block where you except: or except Exception, e: (which is not something you should do anyway/much) you have to prepend except KeyboardInterrupt: raise so that the exception is not "eaten".
I use this for catching a ctrl-c on windows. In case I'm writing to a pipe or file or what have you.. I want to exit gracefully. Below is a toy example
import signal
import sys
def signal_handler(signal, frame):
print('Process Interrupted!\n\a')
sys.exit(0)
signal.signal(signal.SIGINT,signal_handler)
#Rest of your code

Categories

Resources