2015-07-10 59 views
0

我正在測試,看看atexit模塊是否通過嘗試打印到文件正常運行。 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() 

回答

0

您while循環,這我假設你被殺死腳本(意爲port_exit未註冊的功能)退出後註冊功能。如果您在此之前註冊函數,那麼在腳本退出時它應該觸發並寫入文件。

atexit.register(port_exit) 

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