Python读取cmd AVRDUDE来更新arduino

问题描述

我使用连接到 Arduino nano 的 Tkinter 在 python 中创建了一个 GUI。我可以使用我的 GUI 使用 AVRDUDE 在 Arduino 上刷新固件,没有问题,但这会在编程时弹出一个 CMD 框。我想要的是将其重定向或管道到我的 GUI 的文本框。如果我使用普通的 Windows 命令,如 ping、dir 等,这没有问题(下面的示例代码和屏幕截图),但是当我尝试刷新 Arduino 时,它会闪烁但仍在它自己的控制台中并且不会重定向。我猜 AVRDUDE printf 就是这个问题,但有没有办法重定向输出

我也试过在最后添加 "2> e:\\output.txt" 像这个链接 https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer/parsing-output-from-avrdude-w-python 以保存到文件然后我可以读入文件。如果我在 CMD 中这样做,它可以工作,但如果我从 python 中尝试,我得到

参数错误>2

即使我尝试 >> test.txt。

import tkinter as tk
import subprocess,sys

main = tk.Tk()

IP = "ping 192.168.0.1"
date = ["cmd","/C","date","/T"]

arduino = ["W:\\Python\\Hopper_Tester\\update\\avrdude","-CW:\\Python\Hopper_Tester\\update\\avrdude.conf","-patmega328p","-carduino","-PCOM7","-b115200","-D","-Uflash:w:C:\\Users\Frazer Telford\\Documents\\PlatformIO\\Projects\\hopper_test\\.pio\\build\\nanoatmega328\\firmware.hex:i","2>","e:\\flash.txt"]


RUN = IP

textBox = tk.Text(main)
textBox.pack()

def command_one():

    #item = subprocess.Popen(RUN,stdout=subprocess.PIPE,creationflags=subprocess.CREATE_NEW_CONSOLE)
    item = subprocess.Popen(RUN,stdout=subprocess.PIPE)
    #item.communicate()[0]

    # print(f"printing {item}")

    for line in item.stdout:
        output = (line.decode())
        textBox.insert(tk.END,output)
        textBox.see(tk.END)
        main.update_idletasks()

def command_two():
    result = subprocess.run(RUN,text = True)

    for line in result.stdout:
        #output = (line.decode())
        textBox.insert(tk.END,line)
        textBox.see(tk.END)
        main.update_idletasks()


tk.Button(main,text = "Function 1",command = command_one).pack(side=tk.LEFT,padx = 10)
tk.Button(main,text = "Function 2",command = command_two).pack(side=tk.LEFT,padx = 10)




main.mainloop()

enter image description here

解决方法

在花了几个小时之后,我找到了一个有效的修复方法,如果有人有更好的方法,我会很感激你的回复。

def command_one():
item = subprocess.Popen(RUN,stderr=subprocess.PIPE)


for line in item.stderr:
    #output = (line.decode())
    textbox.insert(tk.END,line)
    main.update_idletasks()

textbox.see(tk.END)

我的错误是在我应该查看 stderr 的地方查看 stdout,不知道为什么,但我得到了我需要的输出。

enter image description here