macos: KeyboardInterrupt exception not working w/Phidget22.Devices.DigitalOutput
Posted: Tue Nov 07, 2023 2:27 pm
When using the following to catch ctrl-C on macos the handler is never called if I have also opened a Phidget22.Devices.DigitalOutput device.
I am using a REL1100 4-channel solid state relay with a VINT HUB0000.
Here's my test code. It opens a Phidget22.Devices.DigitalOutput device and runs through a loop counting up to 20.
By default it opens a Phidget22.Devices.DigitalOutput and then sets the dutycycle before entering the loop.
It includes an optional argument to skip opening the Phidget22.Devices.DigitalOutput device.
This is what a normal run looks like.
Here's what the same run looks like when interrupting the loop with ctrl-C. NOTE: the exit_reason: "ctrl-C", IS NOT printed.
Here the same test except I am NOT opening the Phidget22.Devices.DigitalOutput. NOTE: the exit_reason: "ctrl-C", IS printed.
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