Python:使用subprocess运行CMD,用于刷新stm32 uC

2024-09-24 06:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python脚本上闪存stm32时遇到了一些问题。我用的是ST-LINK_CLI.exe,以刷新uC,它在Windows中使用CMD工作,但不能通过python工具工作。你知道吗

我从学校里得到的错误子流程运行(…)是“无法打开文件!”对于我提供的路径,但是相同的路径在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)

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


Tags: path路径脚本cmdoutputcliwindowsstdout
2条回答

你没有解码你的路径,只是把你的字节转换成字符串,所以你得到了一个像这样的路径

"b'C:/Users/U1/Desktop/test.hex'"

尝试解码而不是得到正确的字符串

stlink_output = subprocess.run( ["ST-LINK_CLI.exe", "-c", "ID=0", "SWD", "-P", path.decode(), "-V", "-HardRST", "-Rst"], check=False, stdout=subprocess.PIPE).stdout.decode().splitlines()

如果您确定输出值是text请考虑使用runtext=True参数(如果需要,还可以使用encoding)。你知道吗

只需将路径定义为字符串并使用它(无需编码/解码)。你知道吗

同样对于python3.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)

相关问题 更多 >