I am working with a Python script that runs in a infinite while loop and acquires data from a remote instrument using a socket (Remoteserver) connection over vx11. I want to be able to terminate the script gracefully using the CTRL+C command (SIGINT), which should trigger a routine to acquire the remaining data before breaking the process.
I am aware that I can handle the keyboard interrupt with try: ... while Loop... except KeyboardInterrupt: or finally:
, or by using signal.signal(signal.SIGINT, sigint_handle)
, but the problem I am facing is that when I use CTRL+C to terminate the script, the socket connection to the remote host gets disconnected immediately, preventing me from sending any further commands to the instrument in the acquisition routine.
Is there a way to prevent the disconnection from happening while still being able to terminate the script with CTRL+C
and acquire the remaining data? I suspect that CTRL+C
is being sent to all running jobs, and I would like to have a kind of discipline where only the "foreground" process is terminated first.
This is not working, the Remotehost (vx11) is broke within the first line of sigint_handler already:
import signal
import time
import vxi11
class Program:
def __init__(self, ip_host):
self.instr= vxi11.Instrument(ip_host)
signal.signal(signal.SIGINT, self.sigint_handler)
def run(self):
while self.instr.ask("some commmand..") == True
print("Running...")
time.sleep(1)
data = self.instr.ask("some commmand..")
# etc. ... save data
print("Programm end...")
def sigint_handler(self, signum, frame):
print("CTRL+C recieved.")
data = self.instr.ask("some commmand..")
# etc. ... save data
print("Programm end...")
if __name__ == '__main__':
ip_host = "1.1.1.1"
program = Program(ip_host)
program.run()