0

I'm testing to see if the atexit module runs properly by attempting to print to file. The actual purpose of atexit will be to close the open port, however this is to test if atexit is working in the first place. However, atexit is not printing to file, any ideas why not? Any help is appreciated.

import atexit
import scala5
from scala5 import sharedvars
scalavars = sharedvars()
import serial
myPort=serial.Serial()

myPort.baudrate = 9600
myPort.port = "COM4"
myPort.parity=serial.PARITY_NONE
myPort.stopbits=serial.STOPBITS_ONE
myPort.bytesize=serial.EIGHTBITS
myPort.timeout=2
myPort.writeTimeout=2

try:
    myPort.close()
except:
    print("didn't need to close")

def port_exit():
    fo = open("test.txt", "w")
    fo.write("This works!")
    fo.close()

myPort.open()

while True:
    x = myPort.readline()
    if x == "1\r\n":
        scalavars.door = x
    scala5.ScalaPlayer.Sleep(10)

atexit.register(port_exit)
port_exit()
Gigsa
  • 1

1 Answers1

0

You are registering the function after your while loop, which I am assuming you are exiting by killing the script (meaning the function port_exit isn't registered). If you register the function before the while then it should trigger and write the file when the script exits.

atexit.register(port_exit)

while True:
    x = myPort.readline()
    if x == "1\r\n":
        scalavars.door = x
    scala5.ScalaPlayer.Sleep(10)
Songy
  • 851
  • 4
  • 17