0

我正在atexit通过尝试打印到文件来测试模块是否正常运行。的实际目的atexit是关闭打开的端口,但这是首先测试是否atexit正常工作。但是,atexit不是打印到文件,有什么想法为什么不呢?任何帮助表示赞赏。

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()
4

1 回答 1

0

您在 while 循环之后注册该函数,我假设您通过终止脚本退出(这意味着该函数port_exit未注册)。如果您在 while 之前注册该函数,那么它应该在脚本退出时触发并写入文件。

atexit.register(port_exit)

while True:
    x = myPort.readline()
    if x == "1\r\n":
        scalavars.door = x
    scala5.ScalaPlayer.Sleep(10)
于 2015-07-10T15:07:18.980 回答