Python創建、刪除桌面、啟動組快捷方式的例子分享


一、Python創桌面建快捷方式的2個例子

例子一:

 

代碼如下:

import os
import pythoncom
from win32com.shell import shell    
from win32com.shell import shellcon

 

def createDesktopLnk(filename,lnkname):
    shortcut = pythoncom.CoCreateInstance(    
        shell.CLSID_ShellLink, None,    
        pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)    
    shortcut.SetPath(filename)    
    if os.path.splitext(lnkname)[-1] != '.lnk':    
        lnkname += ".lnk"
    # get desktop path
    desktopPath = shell.SHGetPathFromIDList(shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_DESKTOP))
    lnkname = os.path.join(desktopPath,lnkname)
    shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)  

if __name__ == '__main__':
    createDesktopLnk(u"C:\Python27\python.exe","MyPython")

 

 

例子二:
首先得安裝 ActiveState ActivePython  . 因為這個中帶了 winshell 庫

代碼如下:

from os import path    
import winshell    

  
#----------------------------------------------------------------------  
def create_shortcut_to_desktop(target,title):  
    """Create shortcut to desktop"""  
    s = path.basename(target)    
    fname = path.splitext(s)[0]    
    winshell.CreateShortcut(    
    Path = path.join(winshell.desktop(), fname + '.lnk'),    
    Target = target,    
    Icon=(target, 0),    
    Description=title)  


注:不支持win64

 


二、使用winshell模塊創建、刪除桌面、啟動組快捷方式

當寫好一個應用並發行的時候,我們希望在用戶的桌面上建立快捷方式方便用戶操作,winshell模塊提供了我們需要的功能

下面這個函數將創建程序自身的快捷方式到桌面:

代碼如下:

from os import path  
import winshell  

def create_shortcut_to_desktop():  
    target = argv[0]  
    title = '我的快捷方式' 
    s = path.basename(target)  
    fname = path.splitext(s)[0]  
    winshell.CreateShortcut(  
    Path = path.join(winshell.desktop(), fname + '.lnk'),  
    Target = target,  
    Icon=(target, 0),  
    Description=title)  

 

下面這個函數實現將本程序的快捷方式從桌面刪除:

 

代碼如下:

 def delete_shortcut_from_startup():  
    target = argv[0]  
    s = path.basename(target)  
    fname = path.splitext(s)[0]  
    delfile = path.join(winshell.startup(), fname + '.lnk')  
    winshell.delete_file(delfile) 
 

 

下面這個函數實現了建立快捷方式到啟動組:

代碼如下:

from os import path  
import winshell  

def create_shortcut_to_startup():  
      target = argv[0]  
      title = '我的快捷方式' 
      s = path.basename(target)  
      fname = path.splitext(s)[0]  
      winshell.CreateShortcut(  
      Path = path.join(winshell.startup(),   
      fname + '.lnk'),  
      Target = target,  
      Icon=(target, 0),  
      Description=title) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM