Python程序/PyQt实现开机自启动

相比于修改注册表实现开机自启动,可以直接在windows的本用户目录的自启动文件夹下创建快捷方式同样实现开机自启动,并且无需管理员权限

import os

#注意导包不要使用import win32com,会提示module 'win32com' has no attribute 'client'
#改变导包方式为 from win32com import client后才不会报错
from win32com.client import Dispatch

def auto_start_on():
    # 在该路径下创建快捷方式,指向当前运行的程序
    # 如果已有相同名称的快捷方式也不影响创建
    create_shortcut(get_shortcut_create_path())
def auto_start_off():
    #获取快捷方式的位置,然后再尝试删除
    delete_shortcut(get_shortcut_create_path())

def get_shortcut_create_path():
    # 获取当前系统用户名和快捷方式创建路径
    current_username = os.getlogin()
    full_filename = os.path.basename(__file__)
    filename, ext = os.path.splitext(full_filename)
    shortcut_location = r"C:\Users\{}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\{}.lnk".format(
        current_username, filename)
    #返回快捷方式创建路径
    return shortcut_location
def create_shortcut(shortcut_location):
    # shortcut_location 快捷方式当前所在的位置
    # target_path 快捷方式指向的位置
    target_path = os.path.abspath(__file__)
    shell = Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(shortcut_location)
    shortcut.Targetpath = target_path
    # shortcut.WorkingDirectory = os.path.dirname(target_path)
    # shortcut.IconLocation = target_path
    shortcut.save()

def delete_shortcut(shortcut_location):
    if os.path.exists(shortcut_location):
        try:
            os.remove(shortcut_location)
        except Exception as e:
            print("删除文件失败",e)
    else:
        print("没有找到快捷方式")

if __name__ == '__main__':
    auto_start_on()
    #auto_start_off()
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值