Reputation: 37
I use VS Code to develop python program. And I found it cannot capture the ctrl+C key when using the external terminal, but it worked properly with the integrated terminal.
Here is my python code:
import time
print('press enter to start,and press ctrl+C to stop:')
while True:
input("")
starttime = time.time()
print('Started')
try:
while True:
print('Counting:', round(time.time() - starttime, 3), 'seconds',end='\r')
time.sleep(0.001)
except KeyboardInterrupt:
print('\nEnd')
endtime = time.time()
print('Total Time:', round(endtime - starttime, 3), 'seconds')
break
and here is my lauch.json file with integrated terminal:
{
"stopOnEntry": false,
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
here is my lauch.json file with external terminal:
{
"stopOnEntry": false,
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
}
]
}
With the external terminal, the code cannot stop when I give it a ctrl+C key. I want to figure out why and how to fix this. Thank you for helping.
Upvotes: 0
Views: 1436
Reputation: 396
Using Keyboard interrupts to close your program isn't a great way but if you still want to I think it is ctr + alt + m for VS code. To do it the proper way you should use the keyboard
module:
import keyboard
if keyboard.is_pressed('q'):
print('goodbye')
quit()
As mentioned in the comments, OP wants an error to be excepted in which case just use
raise Exception('Exiting')
In the code:
import keyboard
if keyboard.is_pressed('q'):
print('goodbye')
raise Exception('Exiting')
This can caught by:
except Exiting:
print("Key Board Interupt")
Upvotes: 0