首页 > 解决方案 > 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)

有谁知道,提供的路径有什么问题?我应该使用不同的编码吗?

标签: pythonsubprocess

解决方案


如果您确定输出值是文本,请考虑使用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)

推荐阅读