0

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

我的脚本:

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

4

2 回答 2

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.
于 2013-05-12T18:06:34.410 回答
0

要考虑的模块:时间和系统

#!/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()
于 2013-05-12T18:09:23.817 回答