python 生成Windows快捷方式
此处以虚拟机镜像快捷方式为例
link_filepath:快捷方式的生成路径
win32_cmd:需要执行的应用程序
arg_str:exe的参数
快捷方式的目标:由win32_cmd + arg_str组成
icon_location:快捷方式的图标位置(默认为ico)
working_directory:快捷方式的起始位置
import pythoncom, winshell
def generate_shortcut(shortcut_name):
"""
生成快捷方式
:vm_name:创建的快捷方式名称,默认为vm_name
"""
try:
# 在多线程时需要添加init,告诉Windows需要开一个com对象
pythoncom.CoInitialize()
link_filepath = os.path.join(winshell.desktop(), f"{shortcut_name}.lnk")
if os.path.exists(link_filepath):
os.remove(link_filepath)
win32_cmd = VBOX_MANAGER_EXE_PATH
arg_str = f"startvm {vm_name} --type separate"
my_working = os.path.abspath(os.path.join(VBOX_MANAGER_EXE_PATH, ".."))
with winshell.shortcut(link_filepath) as link:
link.path = win32_cmd
link.description = "description"
link.arguments = arg_str
link.icon_location = (ICON_PATH, 0)
link.working_directory = my_working
pythoncom.CoUninitialize()
except Exception as e:
logger.info(f"generate_shortcut fail:{e}")