Python脚本自动关闭

Python脚本自动关闭,python,timer,serial-port,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.rea

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

我的剧本:

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

您可以使用
时间模块:

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

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

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