繁体   English   中英

Python脚本自动关闭

[英]Python script auto close

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

我的剧本:

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

您可以使用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.

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

#!/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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM