MDK執行python腳本自動修改版本構造時間

平常在寫單片機項目時會加入版本號,編譯時間等。嫌手動修改宏定義麻煩,嘗試使用腳本自動完成,剛好 MDK 也可以指定運行腳本。

腳本語言選擇 Python

方法是 MDK 在編譯代碼前執行 Python 文件,替換指定文件內的字符串。

#define BUILD_NUM           (uint8_t *)"7"
#define BUILD_TIME          (uint8_t *)"2020-05-18 08:55:08"

Option|User 中可以填入腳本語句 python ..\..\tools\build_version.py ..\..\usr_app\usr_service\hw_data.c

注意兩個點:

  • 腳本需要在 build 前執行
  • 勾選腳本執行

參考代碼很簡單,個性化需求自己修改,不會 Python 的搜索學習下吧。

import time
import sys


def update_build_info(version_file_path=""):
    if not version_file_path:
        return

    f = None
    file_data = ""

    try:
        f = open(file=version_file_path, mode='r', encoding='utf-8')
        while True:
            line = f.readline()
            if "#define" in line and "BUILD_TIME" in line:
                _old_str_list = line.split("\"")
                _old_str_list[1] = "\"{0}\"".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                new_str = ""
                for _ in _old_str_list:
                    new_str += _
                line = line.replace(line, new_str)

            if "#define" in line and "BUILD_NUM" in line:
                _old_str_list = line.split("\"")
                _old_str_list[1] = "\"{0}\"".format(int(_old_str_list[1]) + 1)

                new_str = ""
                for _ in _old_str_list:
                    new_str += _
                line = line.replace(line, new_str)

            if line:
                file_data += line
            else:
                break

        f.close()
        f = open(file=version_file_path, mode='w', encoding='utf-8')
        if file_data:
            f.write(file_data)

    except FileNotFoundError:
        print("{0} not found\n".format(version_file_path))
    finally:
        if f and not f.closed:
            print("close file\n")
            f.close()


if __name__ == "__main__":
    # 傳入文件路徑
    arg = sys.argv[1]
    update_build_info(arg)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章