python - Python:使用子进程运行CMD,用来刷stm32 uC
问题描述
我在 python 脚本上闪现 stm32 时遇到了一些麻烦。我正在使用 ST Link Utility 工具提供的 ST-LINK_CLI.exe 来刷新 uC,它通过在 Windows 中使用 CMD 工作,但不能通过 python 工具工作。
我从 subprocess.run(...) 得到的错误是“无法打开文件!” 对于我提供的路径,但相同的路径在 Windows 的 CMD 中可以正常工作。
import subprocess
path = 'C:/Users/U1/Desktop/test.hex'
path = path.encode('utf-8')
stlink_output=[]
try:
stlink_output = subprocess.run(
["ST-LINK_CLI.exe", "-c", "ID=0", "SWD", "-P", str(path), "-V", "-HardRST", "-Rst"],
check=False,
stdout=subprocess.PIPE).stdout.decode().splitlines()
except:
print("An error occured")
print(stlink_output)
有谁知道,提供的路径有什么问题?我应该使用不同的编码吗?
解决方案
如果您确定输出值是文本,请考虑使用run
text=True
参数(encoding
如果需要)。
只需将路径定义为字符串并使用它(无需编码/解码)。
同样对于 python 3.4+,建议使用pathlib
模块(允许稍后在您的代码中进行整洁的检查和用户扩展)。所以代码看起来像:
import subprocess
import pathlib
# `~` gets converted to current user home with expanduser()
# i.e. `C:/Users/U1` in Your case
path = pathlib.Path('~/Desktop/test.hex').expanduser()
if not path.exists():
raise FileNotFoundError(path)
stlink_output = subprocess.run(
["ST-LINK_CLI.exe", "-c", "ID=0", "SWD", "-P", path, "-V", "-HardRST", "-Rst"],
check=False,
# text option without decoding requires py3.7+...
# text=True,
# stdout=subprocess.PIPE).stdout.splitlines()
# ...so this is variant pre python3.7:
stdout=subprocess.PIPE).stdout.decode().splitlines()
print(stlink_output)
推荐阅读
- java - 如何将 JsonNode 实例转换为实际的 pojo
- c# - 将文本块可见性与网格的自定义属性绑定
- java - 如何处理 JAXB 属性中的冒号(:)?
- python - 如何计算第 1 组和第 2 组中出现的数字数量
- sql-server - 查询未显示案例的预期结果
- coq - Coq 中自反传递闭包的符号
- delphi - 当我在 Delphi 中打开表单时,有没有办法默认打开代码(pas)而不是设计(dfm)?
- laravel - 如何提交 Laravel VueJS 动态表单数据?
- plsql - 如何将具有十进制值的数字转换为 PL/SQL 中的浮点数?
- python - 跨平台文件路径的首选 SQLite 数据类型?