2013-05-12 93 views
0

我終於得到了代碼來打印來自串口的細節沒有空行,但我不知道如何使這個腳本自動結束工作。Python腳本自動關閉

我的腳本:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

from serial import Serial 

ser = Serial('/dev/ttyACM0', 9600, 7, 'E', 1) 

while True: 
    # Read a line and convert it from b'xxx\r\n' to xxx 
    line = ser.readline().decode('utf-8')[:-2] 
    print line 

,現在我想開這個腳本 - 打印2-3秒鐘,全自動關閉腳本。那可能嗎?

回答

1

可以使用time模塊:

from serial import Serial 
import sys,time 
ser = Serial('/dev/ttyACM0', 9600, 7, 'E', 1) 

t1 = time.time() 
while time.time() - t1 <= 3: 
    # Read a line and convert it from b'xxx\r\n' to xxx 
    line = ser.readline().decode('utf-8')[:-2] 
    print line 
sys.exit()  #exit script 

幫助time.time

>>> time.time? 
Type:  builtin_function_or_method 
String Form:<built-in function time> 
Docstring: 
time() -> floating point number 

Return the current time in seconds since the Epoch. 
Fractions of a second may be present if the system clock provides them. 
0

模塊來考慮:時間& SYS

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

from serial import Serial 
import time 
import sys 

ser = Serial('/dev/ttyACM0', 9600, 7, 'E', 1) 
num_sleep = 0 
seconds_to_sleep = 3 
while True: 
    if (num_sleep == seconds_to_sleep): 
     break 
    # Read a line and convert it from b'xxx\r\n' to xxx 
    line = ser.readline().decode('utf-8')[:-2] 
    print line 
    time.sleep(1) 
    num_sleep += 1 
sys.exit()