vscode 使用 python 进行 UG 二次开发 实现代码提示功能
vscode 使用 python 进行 UG 二次开发的 实现代码提示功能
用 VSCODE 进行 UG 二次开发的时候, 想要用代码提示的时候,可以用 pydev 插件, 但是,pydev 只有一个月的试用期,那到用 pylance 可不可以有相似的效果吗?
答案是可以。
方法是 自己生成 NXOpen.pyi 文件。
自已写了一段代码,用于简单的生成 这个 文件。
- 先运行这个代码,生成 NXOpen 文件夹,
- 再把这个文件夹移动到 NXBIN/python目录下。
__version__ = "0.0.4"
__author__ = "unmht"
from typing import Dict, Generator, List, Optional
import NXOpen
import types
import os
import re
from importlib import import_module
ugii_base_dir = os.getenv("UGII_BASE_DIR")
pp = os.path.join(str(ugii_base_dir), "nxbin", "python")
imp_mds = {}
for root, dirs, files in os.walk(pp, topdown=True):
if root != pp:
break
for ff in files:
# print(ff)
if str(ff).startswith("NXOpen_") and str(ff).endswith(".pyd"):
module_name = str(ff)[:-4]
# print(module_name)
try:
ms = module_name.split("_")[-1]
imp_mds[ms] = import_module(module_name)
except Exception as e:
print("error:", module_name, e)
class pyibase:
ecpts = [
"NXObject",
"TaggedObject",
"INXObject",
]
def __init__(self) -> None:
self.name: str = ""
self.doc: Optional[str] = ""
self.chdmdls: Dict = {}
self.chdtps: Dict = {}
self.MdDescriptor: Dict = {}
self.GSDescriptor: Dict = {}
self.unct: Dict = {}
self.nxc: Dict[str, "nxoClsAliasType | pyibase"] = {}
self.mthdorbutin: Dict = {}
self.mberDescriptor: Dict = {}
self.tpsinvoke: Dict[str, List] = {}
self.nn: List[str] = []
def dcts(self) -> Generator["pyibase", None, None]:
for dc in [
self.chdmdls,
self.chdtps,
self.MdDescriptor,
self.GSDescriptor,
self.unct,
self.nxc,
self.mthdorbutin,
self.mberDescriptor,
]:
for v in dc.values():
yield v
def addmember(self, m, dm: List[str] = None):
dirm = dir(m)
if dm is not None:
dirm = [i for i in dirm if i not in dm]
for i in dirm:
if i == "GetSession":
print(i)
if not i.startswith("_"):
att = getattr(m, i)
self.nn.append(i)
if isinstance(att, types.ModuleType):
self.chdmdls[i] = nxoModuleType(att)
elif isinstance(att, type):
if i != att.__name__:
self.tpsinvoke[i] = [att.__module__, att.__name__]
elif i not in pyibase.ecpts:
self.chdtps[i] = nxoType(att)
elif isinstance(att, types.MethodDescriptorType):
self.MdDescriptor[i] = nxoMethodDescriptorType(att)
elif isinstance(att, types.GetSetDescriptorType):
self.GSDescriptor[i] = nxoGetSetDescriptorType(att)
elif isinstance(att, types.MemberDescriptorType):
self.mberDescriptor[i] = nxoMemberDescriptorType(att)
else:
_md = att.__class__.__module__
if "NXOpen" in str(_md):
self.nxc[i] = nxoClsAliasType(att, i)
elif i == "ValueOf":
self.mthdorbutin[i] = nxoBuiltinFunctionType(att)
elif isinstance(att, types.BuiltinFunctionType):
self.mthdorbutin[i] = nxoBuiltinFunctionType(
att, cname=self.name
)
else:
assert TypeError(i, att, type(att))
def docs(self, lv: int = 0, mx: int = 130):
dd = str(self.doc)
dd = dd.strip()
dd2 = dd.splitlines()
dd2 = [i.strip() for i in dd2]
ll = mx - lv * 4
yield (lv + 1) * "\t" + "'''"
yield (lv + 1) * "\t" + f"### {self.__class__.__name__}"
for i in dd2:
for k in range(0, len(i), ll):
yield (lv + 1) * "\t" + i[k : min(len(i), k + ll)]
yield (lv + 1) * "\t" + "'''"
def toStr(self, lv: int = 0, mx: int = 130):
yield lv * "\t" + f"{self.name}:-->"
class nxoModuleType(pyibase):
def __init__(self, m: types.ModuleType) -> None:
super().__init__()
assert isinstance(m, types.ModuleType)
self.doc = m.__doc__
self.name = m.__name__.split(".")[-1]
self.addmember(m)
def toStr(self, lv: int = 0, mx: int = 130):
yield lv * "\t" + f"class {self.name}:"
for i in self.docs(lv):
yield i
for dc in self.dcts():
for i in dc.toStr(lv + 1):
yield i
for i, v in self.tpsinvoke.items():
_a = ".".join(v)
yield "\t" + f"{i}={_a}"
class basetps(pyibase):
def __init__(self, m: type, name="") -> None:
super().__init__()
assert name in pyibase.ecpts
self.name = name
self.doc = m.__doc__
self.mo = type.mro(m)
self.addmember(m)
def toStr(self, lv=0, mx=130):
if self.name in ["TaggedObject", "INXObject"]:
yield lv * "\t" + f"class {self.name}(object):"
elif self.name == "NXObject":
yield lv * "\t" + f"class {self.name}(NXOpen.TaggedObject,NXOpen.INXObject):"
else:
yield lv * "\t" + f"class {self.name}(object):"
for i in self.docs(lv):
yield i
for v in self.dcts():
for ss in v.toStr(lv + 1):
yield ss
for i, v in self.tpsinvoke.items():
_a = ".".join(v)
yield lv * "\t" + "\t" + f"{i}={_a}"
class nxoType(pyibase):
def __init__(self, m: type) -> None:
super().__init__()
assert isinstance(m, type)
self.doc = m.__doc__
self.name = m.__name__
self.mo = type.mro(m)
self.sp = self.mo[1]
ll = []
for k in self.mo[1:]:
for s in dir(k):
if not s.startswith("_"):
ll.append(s)
self.addmember(m, ll)
def toStr(self, lv=0, mx=130):
yield lv * "\t" + f"class {self.name}({str(self.sp)[8:-2]}):"
for i in self.docs(lv):
yield i
for v in self.dcts():
for i in v.toStr(lv + 1):
yield i
for i, v in self.tpsinvoke.items():
_a = ".".join(v)
yield lv * "\t" + "\t" + f"{i}={_a}"
pt1 = r":returns:[ \S]*[\n]?\s*:rtype: :py:class:`([\S]+)`"
p1 = re.compile(pt1)
pt2 = r":returns:[ \S]*[\n]?\s*:rtype: list of :py:class:`([\S]+)`"
p2 = re.compile(pt2)
pt3 = r":returns:[ \S]*[\n]?\s*:rtype: ([\S]+)"
p3 = re.compile(pt3)
pt4 = r":returns:[ \S]*[\n]?\s*:rtype: list of ([\S]+)"
p4 = re.compile(pt4)
def findrtype(ss: str):
rtp = ""
r = p1.search(ss)
if r is not None:
rtp = r.groups()[0]
if rtp == "":
r = p2.search(ss)
if r is not None:
rtp = f"List[{r.groups()[0]}]"
if rtp == "":
r = p3.search(ss)
if r is not None:
rtp = r.groups()[0]
if rtp not in ["int", "str", "float", "bool"]:
rtp = ""
if rtp == "":
r = p4.search(ss)
if r is not None:
rtp = r.groups()[0]
if rtp not in ["int", "str", "float", "bool"]:
rtp = ""
else:
rtp = f"List[{rtp}]"
return rtp
class nxoMethodDescriptorType(pyibase):
def __init__(self, m: types.MethodDescriptorType) -> None:
super().__init__()
assert isinstance(m, types.MethodDescriptorType)
self.doc = m.__doc__
self.name = m.__name__
def toStr(self, lv: int = 0, mx: int = 130):
rtp = findrtype(str(self.doc))
if rtp == "":
rr = ""
else:
rr = f"->{rtp}"
if self.name == "Dispose":
yield lv * "\t" + f"def {self.name}(self){rr}:"
else:
yield lv * "\t" + f"def {self.name}(self,*args,**kw){rr}:"
for i in self.docs(lv):
yield i
yield lv * "\t" + "\t" + "..."
class nxoGetSetDescriptorType(pyibase):
def __init__(self, m: types.GetSetDescriptorType) -> None:
super().__init__()
assert isinstance(m, types.GetSetDescriptorType)
self.doc = m.__doc__
self.name = m.__name__
def toStr(self, lv: int = 0, mx: int = 130):
rtp = findrtype(str(self.doc))
yield lv * "\t" + f"@property"
if rtp == "":
yield lv * "\t" + f"def {self.name}(self):"
else:
yield lv * "\t" + f"def {self.name}(self)->{rtp}:"
for i in self.docs(lv):
yield i
yield lv * "\t" + "\t" + "..."
yield lv * "\t" + f"@{self.name}.setter"
if rtp == "":
yield lv * "\t" + f"def {self.name}(self,value):..."
else:
yield lv * "\t" + f"def {self.name}(self,value:{rtp}):..."
yield ""
class nxoMemberDescriptorType(pyibase):
def __init__(self, m: types.MemberDescriptorType) -> None:
super().__init__()
assert isinstance(m, types.MemberDescriptorType)
self.doc = m.__doc__
self.name = m.__name__
self._tp = type(m).__name__
def toStr(self, lv: int = 0, mx: int = 130):
yield lv * "\t" + f"{self.name}:{self._tp}=..."
for i in self.docs(lv):
yield i
class nxoBuiltinFunctionType(pyibase):
def __init__(
self, m: "types.MemberDescriptorType |types.BuiltinMethodType", cname=""
) -> None:
super().__init__()
assert isinstance(m, types.BuiltinFunctionType) and isinstance(
m, types.BuiltinMethodType
)
self.doc = m.__doc__
self.name = m.__name__
self.cname = cname
def toStr(self, lv: int = 0, mx: int = 130):
rtp = findrtype(str(self.doc))
yield lv * "\t" + f"@classmethod"
if self.name == "ValueOf":
yield lv * "\t" + f"def {self.name}(cls,value:int):"
elif rtp != "":
yield lv * "\t" + f"def {self.name}(cls,*args,**kw)->{rtp}:"
elif self.cname != "" and self.name == "Get" + self.cname:
if hasattr(NXOpen, self.cname):
yield lv * "\t" + f"def {self.name}(cls,*args,**kw)->NXOpen.{self.cname}:"
else:
yield lv * "\t" + f"def {self.name}(cls,*args,**kw)->{self.cname}:"
else:
yield lv * "\t" + f"def {self.name}(cls,*args,**kw):"
for i in self.docs(lv):
yield i
yield lv * "\t" + "\t" + "..."
class nxoClsAliasType(pyibase):
def __init__(self, m, name="") -> None:
super().__init__()
_md = m.__class__.__module__
assert "NXOpen" in str(_md)
self.doc = m.__doc__
self.name = m.__name__ if hasattr(m, "__name__") else name
self.attp = str(m.__class__.__name__)
self.body = m
def toStr(self, lv=0, mx=130):
nn = self.attp
if hasattr(NXOpen, nn):
att = getattr(NXOpen, nn)
if isinstance(att, type):
nn = f"NXOpen.{nn}"
else:
nn = self.body.__class__.__module__ + "." + self.body.__class__.__name__
if self.name == "KeyPerformanceInterface":
print(self.name, f"{self.name}:{nn}=...")
yield lv * "\t" + f"{self.name}:{nn}=..."
for i in self.docs(lv - 1):
yield i
class mainModules(pyibase):
def __init__(
self,
) -> None:
super().__init__()
m = NXOpen
self.doc = m.__doc__
self.name = m.__name__
self.addmember(m)
for i in pyibase.ecpts:
self.chdtps[i] = basetps(getattr(NXOpen, i), i)
for k, v in imp_mds.items():
self.chdmdls[k] = nxoModuleType(v)
def pyi(self):
mm = self
if not os.path.exists("./NXOpen/"):
os.mkdir("./NXOpen")
if not os.path.exists("./NXOpen/clss/"):
os.mkdir("./NXOpen/clss/")
p11 = "./NXOpen/"
p22 = os.path.join(p11, "clss/")
with open(os.path.join(p11, "__init__.py"), "w", encoding="utf8") as f:
m: nxoModuleType
for v in mm.chdmdls.values():
m = v
mn = m.name.split(".")[-1]
mName = mn + ".pyi"
with open(os.path.join(p11, mName), "w") as f2:
f2.write("import NXOpen\n")
f2.write("from typing import List\n")
for _s in m.toStr():
f2.write(_s + "\n")
f.write(f"from .{mn} import {mn} as {mn}" + "\n")
f.write(f"from ._nxopen import *\n")
with open(os.path.join(p11, "_nxopen.pyi"), "w", encoding="utf8") as f2:
m2: nxoType
f2.write("import NXOpen\n")
f2.write("from typing import List\n")
for k, v in mm.chdtps.items():
m2 = v
nn = m2.name
f2.write(f"from .clss.{nn} import {nn} as {nn}" + "\n")
with open(
os.path.join(p22, f"{nn}.pyi"), "w", encoding="utf8"
) as f3:
f3.write("import NXOpen\n")
f3.write("from typing import List\n")
for _s in m2.toStr():
f3.write(f"{_s}\n")
if __name__ == "__main__":
def main():
mainModules().pyi()
main()
vscode 使用 python 进行 UG 二次开发 实现代码提示功能的更多相关文章
- SkylineDemoForWeb JavaScript二次开发示例代码
SkylineDemoForWeb JavaScript二次开发示例代码 http://files.cnblogs.com/files/yitianhe/SkylineDemoForWeb.zip
- Python什么是二次开发的意义?python在.net项目采用
任何人都知道python在.net该项目是做什么的啊? 辅助用途,用作"二次开发"..net站点的话python主要是CGI才用.能够用python编写B/S程序. 解释一下二次开 ...
- Autocad中使用命令来调用python对Autocad二次开发打包后的exe程序
在Autocad中直接调用Python二次开发程序是有必要的,下面介绍一种方法来实现这个功能: 其基本思路是:先将二次开发的程序打包为可执行程序exe,然后编写lsp文件,该文件写入调用exe程序的语 ...
- destoon二次开发基础代码
标签调用规则 http://help.destoon.com/develop/22.html 数据字典 http://help.destoon.com/dict.php destoon各类调用汇总 h ...
- AE二次开发中几个功能速成归纳(符号设计器、创建要素、图形编辑、属性表编辑、缓冲区分析)
/* * 实习课上讲进阶功能所用文档,因为赶时间从网上抄抄改改,凑合能用,记录一下以备个人后用. * * ----------------------------------------------- ...
- python之saltstack二次开发
一.salt的概念 salt是一个配置管理系统,能够维护预定义状态的远程节点(比如,确保指定的报被安装,指定的服务在运行).一个分布式远程执行系统,用来在远程节点(可以是单个节点,也可以是任意规则挑选 ...
- UG二次开发-CAM-获取修改路径参数
项目中要获取路径参数,网上大多是C++的例子,而本项目是用C#写的,探索了下,记录下. 以获取某条路径的刀具号为例,其他参数依此类推. using System; using System.Colle ...
- 【UG二次开发】获取系统信息UF_ask_system_info
获取系统信息可以使用这个函数UF_ask_system_info 下面是例子: 1 extern DllExport void ufsta(char *param, int *returnCode, ...
- UG二次开发-CAM-执行方式
以C#开发为例,通常先用[操作记录]功能录制关键代码,得到一个.cs文件. (1)可以直接使用[播放操作记录]的方式执行该.cs文件. (2)可以建立一个C#的类库工程,将上述.cs文件加载进去,添加 ...
- 【UG二次开发】 UF_OBJ_ask_name 获取对象名字
代码 char name[256]; UF_OBJ_ask_name(objTag, name);
随机推荐
- 一键接入大模型:One-Api本地安装配置实操
前言 最近准备学习一下 Semantic Kernel, OpenAI 的 Api 申请麻烦,所以想通过 One-api 对接一下国内的在线大模型,先熟悉一下 Semantic Kernel 的基本用 ...
- java代码审计跨站脚本(XSS)--反射型
一.基础:跨站脚本(Xss) 一.原理: 恶意攻击者往web页面里插入恶意js代码,而在服务端没有对数据进行严格的过滤.当用户浏览页面时,js代码必须在该html页面中(hrml必须要存在这个而已艾玛 ...
- CSS样式(第三篇)
<div class="box1"> <div class="line"></div> <div class=&q ...
- 【漏洞分析】HPAY 攻击事件分析
背景 造成本次攻击的原因是关键函数的鉴权不当,使得任意用户可以设置关键的变量值,从而导致攻击的发生. 被攻击合约:https://www.bscscan.com/address/0xe9bc03ef0 ...
- 关于URP14绘制全屏Blit后处理的改动
最近用回URP,发现RendererFeature这部分改动很大,启用了之前HDRP的RTHandle,RTHandle的设计类似于优化版本的RenderTexture, 可以统一控制缩放或者并非一对 ...
- Aliplayer通过HLS流式播放Aliyun Mps(媒体处理)转码的加密视频
前言 公司需求,上传的视频需要加上公司Logo,同时播放需要采用流式播放禁止下载. 现有的环境在阿里云上,所以自然想到了阿里云的产品[媒体处理]的转码功能. 转码配置 配置比较简单,采用阿里云HLS标 ...
- 4G EPS 中的 PLMN 选择
目录 文章目录 目录 前文列表 PLMN 选择 前文列表 <4G EPS 中的系统消息类型> PLMN 选择 UE 开机后的第一件事情就是完成小区搜索,即完成和 eNB 的牵手.在牵手成功 ...
- 【漏洞复现】CVE-2023-27372 RCE漏洞
产品介绍 SPIP是一个互联网发布系统,其中非常重视协作工作,多语言环境和Web作者的易用性.它是自由软件,在GNU/GPL许可证下分发.这意味着它可以用于任何互联网站点,无论是个人的还是机构的,非营 ...
- NET9 AspnetCore将整合OpenAPI的文档生成功能而无需三方库
OpenAPI 规范是用于描述 HTTP API 的标准.该标准允许开发人员定义 API 的形状,这些 API 可以插入到客户端生成器.服务器生成器.测试工具.文档等中.尽管该标准具有普遍性和普遍性, ...
- uniapp uni-number-box组件 步长为1,还能输入小数思路分享
正常情况,输入了步长为1,是无法在输入小数的.需求是要能输入一位小数,但如果直接步长设为0.1,又不能按1这样递增,输入数量上用起来肯定很麻烦. 于是我就想了一个折中方法,步长设为:1.01,然后值改 ...