I have a python script that receives stock ticks continuously. I use Ctrl + C to stop the script when I want.
I wish to store the ticks in a dataframe when I use CTRL + C and then script should stop.
How can I do that?
Any help is appreciated.
You could catch the KeyboardInterrupt error, then save the appropriate files and exit. I'd recommend putting a way of exiting different from ctrl + c, though.
try:
# code
except KeyboardInterrupt:
# save and exit gracefully
Related
Context:
I have a running python script. It contains many os.system("./executableNane") calls in a loop.
If I press ctrl + C, it just stops the execution of the current ./executableNane and passes to the next one.
Question:
How to stop the execution of the whole script and not only the execution of the current executable called?
Please note that I have read carefully the question/answer here but even with kill I can kill the executable executableNane but not the whole script (that I cannot find using top).
The only way I have to stop the script (without reboot the system) is to continue to press ctrl + C in a loop as well until all the tests are completed.
You can use subprocess and signal handlers to do this. You can also use subprocess to receive and send information via subprocess.PIPE, which you can read more about in the documentation.
The following should be a basic example of what you are looking to do:
import subprocess
import signal
import sys
def signal_handler(sig, frame):
print("You pressed Ctrl+C, stopping.")
print("Signal: {}".format(sig))
print("Frame: {}".format(frame))
sys.exit(123)
# Set up signal handler
signal.signal(signal.SIGINT, signal_handler)
print("Starting.")
while True:
cmd = ['sleep', '10']
p = subprocess.Popen(cmd)
p.wait()
if p.returncode != 0:
print("Command failed.")
else:
print("Command worked.")
The other solution to the question (by #Quillan Kaseman) is much more elegant compared with the solution I have found. All my problems are solved when I press Ctrl + Z instead of Ctrl + C.
Indeed, I have no idea why with Z works and with C does not. (I will try to look for some details later on).
In my current windows 10 version (10.0.18362) it does not work to cancel a python program with Ctrl + C when running in CMD.
I dont know if it has to do with it, I just want to state that the main Thread has finished but another thread is running when I try to hit Ctrl + C.
What can I do to get a KeyboardInterrupt Exception that I urgently need in order to close the socket that is in use?
Currently whenever I press CTRL + Z on a lengthy script I was given, it immediately terminates the script ([1+] stopped(SIGTSTP) ./test.py) which is what I want, but it also leaves the python2 process running (when I type ps to look at processes), which forces me to use killall -9 python2, which I do not want to do every time. Is there a way to immediately terminate a script that doesn't leave the python2 process running in the background?
There is no SIGTSTP currently in the code that I see but I did try using the following code with no luck. It didn't even exit the script when I pressed CTRL + Z.
def handler(signum, frame):
sys.exit("CTRL+Z pressed. Exiting Test")
signal.signal(signal.SIGTSTP, handler)
SIGSTP is a signal to suspend a process, it sounds like you want to terminate a process. You can try sending Ctrl-C or CTRL-D instead, which should send a SIGINT signal.
I believe you could also try CTRL-\ which sends SIGQUIT.
Use Ctrl + C. SIGTSTP suspends the process, hence why it keeps it open, but does not terminate it.
(Note: On a Linux terminal use Ctrl + \, otherwise use Ctrl + C or Ctrl + D)
Or just use sys.exit()
Is there a proper way to create a script that loops through files in a folder and executes a subprocess that can be externally killed with Ctrl C? I have something like the following embedded in a pipeline and cannot Ctrl C it from the command line when the main process is killed.
Example script:
import subprocess
import os
import sys
input_directory = sys.argv[1]
for file in os.listdir(os.path.abspath(input_directory)):
output = file + "_out.out"
command = ['somescript.py', file, output]
try:
subprocess.check_call(command)
except:
print "Command Failed"
I would then execute program:
Example_script.py /path/to/some/directory/containing/files/
While it is looping, if I see the command failed, I want use Ctrl C. However, it fails and continues to run additional subprocesses despite the main script has been destroyer with Ctrl C. Is there a proper way to write something like this that can kill the childs (additional subprocess) with Ctrl C?
Any help, or pointing me in the direction is appreciated greatly. I am currently looking for a good method to do.
What you have in your try/except block is too permissive, such that when Ctrl+C is pressed, the KeyboardInterrupt exception is also handled by that same exception handler as the one that print "Command Failed", and as that is now properly handled there, the flow of the program is continued through the for loop. What you should do is:
Replace except: with except Exception: so that the KeyboardInterrupt exception will not be trapped, such that any time Ctrl+C is pressed the program will terminate (including subprocesses that isn't stuck in some non-terminatable state);
After the print statement, break out of the loop to prevent further execution from happening, if that is the intended behavior that you want this program to do.
You can catch KeyboardInterrupt, that way you can deal with Ctrl+C in whatever manner you want.
import subprocess
import os
import sys
input_directory = sys.argv[1]
for file in os.listdir(os.path.abspath(input_directory)):
output = file + "_out.out"
command = ['somescript.py', file, output]
try:
subprocess.check_call(command)
except KeyboardInterrupt as e:
print "Interrupted"
sys.exit(1)
except:
print "Command Failed"
However I agree with the other posters in that your exception is too vague, and you should be more specific in what can and can't fail.
I think Ctrl + Z can also help you to push the execution to background and suspended.
Python fails to quit when using Ctrl-C in Powershell/Command Prompt, and instead gives out a "KeyboardInterrupt" string.
Recently I've reinstalled Windows 10. Before the reinstall Ctrl-C quit python (3.5/2.7) fine, with no output.
Does anyone know why this has started happening? Whether it's just a simple setting?
The only difference I can think of is I'm now on python 3.6. Ctrl-D works in Bash on Ubuntu on Windows, and Ctrl-C works fine in an activated anaconda python2 environment for quitting python.
I had this issue with Windows 10 Pro Build 18363 and Python 3.8.1. I was running some python scripts and was unable to stop some with CTRL + C, but CTRL + BREAK worked every time. The Windows Docs had this to say:
The CTRL+C and CTRL+BREAK key combinations receive special handling by console processes. By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input...
CTRL+BREAK is always treated as a signal, but an application can change the default CTRL+C behavior in two ways that prevent the handler functions from being called:
The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT input mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
When SetConsoleCtrlHandler is called with NULL and TRUE values for its parameters, the calling process ignores CTRL+C signals. Normal CTRL+C processing is restored by calling SetConsoleCtrlHandler with NULL and FALSE values. This attribute of ignoring or not ignoring CTRL+C signals is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.
Thus, CTRL + C seems to be a SIGINT and its actions can be modified by the program you are running. It seems that Python on Windows has been coded in such a way that CTRL + C is being processed as keyboard input rather than the SIGINT we are expecting. Fortunately for me I have the CTRL + BREAK keys on my keyboard and this works every time.
For those of you who dont have BREAK on your keyboard, you can use the Windows On Screen virtual Keyboard.
Press win key + r to open the run application program.
Type oskand press ok
On the virtual keyboard, press ctrl + ScrLk and this should kill the program.
This stack thread has some other methods you can try if ctrl + ScrLk doesnt work on the virtual keyboard.
You can type
CTRL + Z,
then hit ENTER to exit python from powershell.
Powershell Screenshot
This is a bug that recently appeared in Windows 10 Insider build 15002.
A work around is to change the Mapped Keys from Ctrl C to something like Ctrl K
If you are not familar how to do this, You can look up or at stty -a
You can run this command on each bash session that will map your Terminate to Ctrl + K
stty intr \^k
As a TEMP solution you could include this in your Bashrc so it is executed on each new session
This bug has been reported already on Github #1569
In my case, I found out that right ctrl + c does the trick in anaconda3 powershell - so no remapping necessary - I'm on Windows 10.
That worked like magic
If you have a laptop with Fn key, tap:
Ctrl + Fn + S
Source:
https://www.dell.com/community/Laptops-General-Read-Only/break-key-alternative/td-p/3826467
When you press Control C, a KeyboardInterrupt exception is thrown. If it isn't stopping the code, the best thing to do is to add a try statement into your code which catches KeyboardInterrupt
try:
....
except KeyboardInterrupt:
exit()
The code is just off the top of my head so sorry if something is wrong.
EDIT: Ctrl Break or on some keyboards Ctrl Pause instantly stops python code apparently.
Hitting Esc button on the upper corner of the keyboard seems to work for me on Windows-7, inside Spyder with numpy running, for Python 3.+
It broke the infinite ...: on an erroneous syntax in the interactive script
When I used to press Ctrl-C, python was quit normally without any output.
I really don't remember when I can quit python with Ctrl + C. In my memory, Ctrl + C always give me KeyboardInterrupt.
I also counldn't find an answer explaining why Ctrl + C can't quit the python in shell. FYI, Ctrl + D and Ctrl + \ can quit python for different reasons. See #Gilles's answer here. https://superuser.com/questions/169051/whats-the-difference-between-c-and-d-for-unix-mac-os-x-terminal
But I think how to handle Ctrl + C is merely a decision of the program. Yes, I think it totally depends on how the program would like to handle it. See the example I write below.
test.c
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static void ctrlC_Handler(int sig){
if(sig == SIGINT){
printf("(:KeyboardInterrupt:)\n");
printf(">>>");
signal(SIGINT, ctrlC_Handler);
}
}
static void welcome(){
printf("Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)\n");
printf("[GCC 7.3.0] on linux2\n");
printf("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n");
printf(">>>");
fflush(stdout);
}
int main(){
welcome();
signal(SIGINT, ctrlC_Handler);
for(;;){
pause();
}
return 0;
}
compile it with gcc test.c and execute it ./a.out. Try pressing Ctrl + C, you can see at least it mimics the behaviour(output) of the python program when you input Ctrl + C.
So, in my opinion, it's nothing special, but a human/programmer/author's decision on how to handle it.