Python脚本自动关闭

时间:2013-05-12 18:02:39

标签: python timer serial-port

我终于得到了从串口打印细节而没有空行的代码,但我不知道如何让这个脚本自动结束。

我的剧本:

#!/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秒并自动关闭脚本。这可能吗?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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()