Dump command’s script

加分題第一題,用 python 開起序列埠,然後把檔案內容寫進去。連到實體機測試時會發現 command 的處理不是完全即時的,所以加了一段緩衝時間,避免 buffer 被吃滿或是讀到錯誤的 command。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import serial
import sys
import time

ser = serial.Serial('/dev/ttyUSB0', 115200)

try:
    filename = sys.argv[1]
except(IndexError):
    print("Need filename!")
    exit(1)

try:
    with open(filename) as f:
        for line in f:
            ser.write(str.encode(line))
            time.sleep(0.1)
except(FileNotFoundError):
    print("File Not Found!")
    exit(1)

input.txt

1
2
3
help
timestamp
reboot
comments powered by Disqus