(21)python开发经验 --- python代码将dll添加进临时环境变量
·
| 更多精彩内容 |
|---|
| 👉内容导航 👈 |
| 👉Qt开发 👈 |
| 👉python开发 👈 |
1、pycharm插件离线安装
-
下载后是一个zip包;
-
打开【文件】【设置】,选中【插件】,点击设置图标,【从磁盘安装插件】;

2、python实现类似C++中将结构体转为二进制的功能
-
在C/C++中传递数据+中传递数据常用方式为
struc Frame{ int a; int b; }; Frame frame; char* buf = new[sizeof(Frame)]; memcpy(buf, &frame, sizeof(Frame)); -
在python中不能直接操作内存,也没有memcpy,可以使用其他方式实现类似功能;
import numpy as np class CmdHead: def __init__(self): self.head = np.uint32(0x11223344) self.length = np.uint32(0) self.id = np.uint32(0) class CmdBody: def __init__(self, cmd_id=0, address=0, length=0): self.cmd_id = np.uint32(cmd_id) self.address = np.uint64(address) self.length = np.uint64(length) def toBody(self, frame_buf): self.cmd_id = int.from_bytes(frame_buf[0:4], "little") self.address = int.from_bytes(frame_buf[4:12], "little") self.length = int.from_bytes(frame_buf[12:20], "little") def get_cmd_id(): # 初始化静态变量 if not hasattr(get_cmd_id, 'count'): get_cmd_id.count = 0 get_cmd_id.count += 1 return get_cmd_id.count def build_frame(body): frame_len = 0 for key, value in vars(body).items(): if isinstance(value, np.uint32): frame_len += 4 elif isinstance(value, np.uint64): frame_len += 8 else: print("Error1:" + key) head = CmdHead() head.length = np.uint32(frame_len + 8) head.id = np.uint32(get_cmd_id()) frame_buf = head.head.tobytes() + head.length.tobytes() + head.id.tobytes() # 遍历class中所有遍历,并转换为字节流 for _, value in vars(body).items(): if isinstance(value, np.uint32) or isinstance(value, np.uint64): frame_buf += value.tobytes() else: print("Error2") return frame_buf # 封装命令 read_efuse = CmdBody(0xaa112233, 0x1000, 16) erase_range = CmdBody(0xaa112244, 0x2000, 100) buf = build_frame(read_efuse) print(buf.hex(" ")) buf = build_frame(erase_range) print(buf.hex(" ")) def frame_type(frame_buf): cmd_id = int.from_bytes(frame_buf[0:4], "little") if cmd_id == 0xaa112233: cmd_body = CmdBody() cmd_body.toBody(frame_buf) print(hex(cmd_body.cmd_id), hex(cmd_body.address), cmd_body.length) elif cmd_id == 0xaa112244: cmd_body = CmdBody() cmd_body.toBody(frame_buf) print(hex(cmd_body.cmd_id), hex(cmd_body.address), cmd_body.length) else: return "unknown" frame_type(buf[12:])
3、python代码将dll添加进临时环境变量
- 这段代码主要用于动态修改当前进程的环境变量
PATH,以便程序能够加载指定目录下的动态链接库或可执行文件; - 修改
os.environ仅对当前 Python 进程及其子进程有效,不会永久修改系统环境变量。
import os
def add_dll_directory(dll_path):
"""
将DLL目录添加到环境变量中
"""
if os.path.exists(dll_path):
# 添加到PATH环境变量开头
print(os.pathsep)
os.environ['PATH'] = dll_path + os.pathsep + os.environ.get('PATH', '')
print(f"已添加 {dll_path} 到环境变量")
else:
print(f"路径 {dll_path} 不存在")
add_dll_directory("./")
更多推荐


所有评论(0)