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

考慮すべきモジュール: time & 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()
于 2013-05-12T18:09:23.817 に答える