如何通过Python脚本向MicroPython环境的树莓派Pico上传文件?
解决Raspberry Pi Pico的MicroPython文件上传脚本问题
你的问题出在rshell启动后进入了交互式模式,而subprocess.run无法自动向交互式shell输入后续命令。不用额外安装库,换用rshell的非交互模式就能解决,直接通过命令行参数传递要执行的操作序列。
可行的脚本实现
以下是修改后的Python脚本,直接用rshell的-c参数执行连接和文件上传命令,无需进入交互界面:
import subprocess import os # 定义虚拟环境路径和要上传的文件路径 venv_dir = "venv" target_file = "your_generated_file.py" # 替换成你的目标生成文件 pico_port = "COM3" # 创建并激活虚拟环境,安装依赖 if not os.path.exists(venv_dir): subprocess.run(["python", "-m", "venv", venv_dir], check=True) # Windows下激活虚拟环境并安装依赖 activate_script = os.path.join(venv_dir, "Scripts", "activate.bat") install_cmd = f'"{activate_script}" && pip install rshell pyreadline3' subprocess.run(install_cmd, shell=True, check=True) # 用rshell非交互模式执行连接和上传命令 rshell_cmd = f'"{activate_script}" && rshell -c "connect serial {pico_port}; cp {target_file} /pyboard/"' result = subprocess.run(rshell_cmd, shell=True, capture_output=True, text=True) # 输出执行结果 print("执行输出:", result.stdout) if result.stderr: print("错误信息:", result.stderr)
关键说明
rshell -c "命令1; 命令2":通过-c参数直接传递要执行的命令序列,用分号分隔多个操作,彻底避开交互模式。/pyboard/是rshell对Pico文件系统的默认挂载路径,上传的文件会保存在Pico的根目录下。- 确保
COM3是Pico实际占用的串口,可在设备管理器中查看确认端口号。 - 如果上传失败,检查Pico是否正常运行MicroPython、串口是否被其他程序占用。
内容的提问来源于stack exchange,提问作者Chickpeaplane
相关产品推荐
相关产品推荐

