Code: Select all
try
code ...
except KeyboardInterrupt
ctrl-C exception handling code ...
Here's my test code. It opens a Phidget22.Devices.DigitalOutput device and runs through a loop counting up to 20.
Code: Select all
from Phidget22.Phidget import *
from Phidget22.Devices.DigitalOutput import *
import time
import argparse
open_phidget = True
parser = argparse.ArgumentParser(
description='show phidget python issue w/ctrl-C on macos.')
parser.add_argument('--open-phidget', default=open_phidget, action=argparse.BooleanOptionalAction,
help=f"disable to skip opening phidget: {open_phidget}")
args = parser.parse_args()
open_phidget= args.open_phidget
def main():
exit_reason = "count completed"
running = True
count = 1
max_count = 20
sleep = 0.1
d0 = DigitalOutput()
if open_phidget:
d0.openWaitForAttachment(5000)
d0.setDutyCycle(0.5)
print(f"\nCounting to {max_count} over {max_count * sleep} seconds. Try interrupting with ctrl-C")
try:
while running:
print(count)
count += 1
running = count <= max_count
time.sleep(sleep)
except KeyboardInterrupt:
exit_reason = "ctrl-C"
print(f"\nExit reason: {exit_reason}\n")
if open_phidget:
d0.close()
main()
It includes an optional argument to skip opening the Phidget22.Devices.DigitalOutput device.
Code: Select all
% python test-ctrl-c.py --help
usage: test-ctrl-c.py [-h] [--open-phidget | --no-open-phidget]
show phidget python issue w/ctrl-C on macos.
options:
-h, --help show this help message and exit
--open-phidget, --no-open-phidget
disable to skip opening phidget: True
Code: Select all
Counting to 20 over 2.0 seconds. Try interrupting with ctrl-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Exit reason: count completed
Code: Select all
% python test-ctrl-c.py --open-phidget
Counting to 20 over 2.0 seconds. Try interrupting with ctrl-C
1
2
3
4
5
6
7
8
9
10
^C%
Code: Select all
% python test-ctrl-c.py --no-open-phidget
Counting to 20 over 2.0 seconds. Try interrupting with ctrl-C
1
2
3
4
5
6
^C
Exit reason: ctrl-C