**********************实现右键功能**********************
程序名称:install.py
环境win10+python3
安装库:pip install winshell
#传递参数为xxx.py(1 非全路径名称;2 需要和install.py同级目录)
#生成xxx_bat.bat文件,
# 并且在......\AppData\Roaming\Microsoft\Windows\SendTo下生成xxx_bat右键快捷图标
使用方法:任何文件右键选择send to找到xxx_bat执行
程序code如下:
#coding:utf-8
#python:>=3.6
"""
功能:生成bat文件并且创建lnk,最后追加到右键的 "sendto"
sendto中的快捷键名称为传入的py程序的文件名称
need lib:
pip install winshell
"""
import os
import sys
import winshell
def delete_shortcut_from_sendto(target):
'''
@Time : 2021/10/19 09:47:14
@功能 : 删除快捷键
'''
s = os.path.basename(target)
fname = os.path.splitext(s)[0]
delfile = os.path.join(winshell.sendto(), fname + '.lnk')
print(delfile)
if os.path.isfile(delfile):
winshell.delete_file(delfile)
# 测试完成
def create_shortcut_to_sendto(target, title="功能描述..."):
'''
@Time : 2021/10/19 09:47:51
@功能 : 创建快捷键
'''
link_name = os.path.splitext(os.path.basename(target))[0]
path_ = os.path.join(winshell.sendto(), link_name + '.lnk')
print(path_)
winshell.CreateShortcut(
Path=path_,#右键sendto快捷方式
Target=target,
Icon=(target, 0),
Description=title)
def CreateBat(python_pro):
'''
@Time : 2021/10/19 09:48:40
@功能 : 生成或者更新bat文件
'''
new_path = None
if os.path.split(python_pro)[0] =="":
new_path = os.path.dirname(os.path.realpath(__file__))
print(rf"未提供路径,在{new_path}目录生成bat文件")
else:
new_path = os.path.dirname(python_pro)
print(rf"提供路径,在{new_path}")
cmd = "python {}\\{} %*".format(new_path, os.path.basename(python_pro))
bat_name = os.path.splitext(os.path.basename(python_pro))[0]
bat_path = "{}\\{}.bat".format(new_path, bat_name)
with open(bat_path, "w") as f:
f.write(cmd)
return bat_path
if __name__ == "__main__":
bat_path = CreateBat(sys.argv[1])
if os.path.isfile(bat_path):
print("{} exists".format(bat_path))
delete_shortcut_from_sendto(bat_path)
create_shortcut_to_sendto(os.path.basename(bat_path))
# os.system("pause")