0

atexitファイルへの出力を試みて、モジュールが正しく動作するかどうかをテストしています。willの実際の目的は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 に答える