写一个python脚本,可以支持传入两个参数,参数1:指定log文件,参数2:指定uart设备端,参数3:指定uart波特率, 参数4: 指定timeout时间。脚本中写一个函数,将uart的输出打印到log文件, 并打印出log文件的路径。并写一个help,提示脚本如何使用.
时间: 2024-09-07 20:01:56 浏览: 45
M1 IC卡读写UART接口模块YHY502CTG技术参数
```python
import logging
import serial
import argparse
def print_uart_to_log(file_name, uart_device, baud_rate, timeout):
log_format = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(filename=file_name, level=logging.INFO, format=log_format)
try:
ser = serial.Serial(uart_device, baud_rate, timeout=timeout)
while True:
line = ser.readline().decode()
if line:
logging.info(line.strip())
print(f"Uart output logged: {line.strip()}")
except Exception as e:
logging.error("Error reading from UART: ", exc_info=True)
print(f"Error: {str(e)}")
def main():
parser = argparse.ArgumentParser(description="Script to print UART data to a log file.")
parser.add_argument("-f", "--file", dest="logfile", required=True, help="Path to the log file")
parser.add_argument("-u", "--uart", dest="uart_device", required=True, help="Serial port device (e.g., /dev/ttyUSB0)")
parser.add_argument("-b", "--baud", type=int, dest="baud_rate", required=True, help="UART baud rate")
parser.add_argument("-t", "--timeout", type=float, dest="timeout", default=1, help="Timeout in seconds for serial read")
args = parser.parse_args()
print_uart_to_log(args.logfile, args.uart_device, args.baud_rate, args.timeout)
if __name__ == "__main__":
main()
#
阅读全文