2011-07-24 49 views
8

¿Cómo se cambia un acceso directo de Windows utilizando Python?Modificar accesos directos a Windows usando Python

p. Ej. a partir de:

H:\My Music\some_file.mp3 

a:

D:\Users\Myself\My Music\some_file.mp3 
+0

Has probado esto: http://stackoverflow.com/questions/6805881/modify-windows-shortcuts-using-python/6806426 # 6806426? – Hnatt

+0

[Pregunta de seguimiento para accesos directos de Unicode] (http://stackoverflow.com/questions/6916069/modify-windows-unicode-shortcuts-using-python) – Jonathan

Respuesta

7

Aquí hay otra manera más apropiada de hacerlo en Python con la biblioteca de Winshell: Using Python to create Windows shortcuts. En su caso, el código se verá así:

import os, winshell 
from win32com.client import Dispatch 

desktop = winshell.desktop() 
path = os.path.join(desktop, "some_file.mp3.lnk") 
target = r"D:\Users\Myself\My Music\some_file.mp3" 
wDir = r"D:\Users\Myself\My Music" 
icon = r"D:\Users\Myself\My Music\some_file.mp3" 

shell = Dispatch('WScript.Shell') 
shortcut = shell.CreateShortCut(path) 
shortcut.Targetpath = target 
shortcut.WorkingDirectory = wDir 
shortcut.IconLocation = icon 
shortcut.save() 

El atajo existente debe eliminarse o reescribirse. Si lo necesita para el procesamiento por lotes de archivos de acceso directo, entonces creo que hay alguna manera de leer las rutas de los accesos directos existentes, pero no pude encontrarlo.

+1

'winshell' probablemente no es exagerado. todavía no está incorporado. Y solo para obtener la ubicación del escritorio de los usuarios también puede hacer: 'os.path.join (os.getenv ('perfil de usuario'), 'escritorio')' – ewerybody

2

Otro método es detallada here

utilizar el ejemplo de actualización de acceso directo. Puede , modificarlo y luego usar el método shortcut.SetPath() para configurarlo.

4

La solución de Jonathan funciona a la perfección. Esta es la función útil que produje implementando esto. Simplemente pase el nombre del archivo de acceso directo (por ejemplo, "Mozilla Firefox.lnk", no es necesario especificar la ruta de archivo completa) y el nuevo destino de acceso directo, y se modificará.

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

def short_target(filename,dest): 
    shortcut = pythoncom.CoCreateInstance (
     shell.CLSID_ShellLink, 
     None, 
     pythoncom.CLSCTX_INPROC_SERVER, 
     shell.IID_IShellLink 
    ) 
    desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) 
    shortcut_path = os.path.join (desktop_path, filename) 
    persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile) 
    persist_file.Load (shortcut_path) 
    shortcut.SetPath(dest) 
    mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0) 
    shortcut.SetWorkingDirectory (mydocs_path) 
    persist_file.Save (shortcut_path, 0) 

La única dependencia es la biblioteca pywin32. También tenga en cuenta que uno puede especificar opciones y argumentos en su destino de acceso directo. Para poner en práctica, a llamarlo:

short_target("shortcut test.lnk",'C:\\') #note that the file path must use double backslashes rather than single ones. This is because backslashes are used for special characters in python (\n=enter, etc) so a string must contain two backslashes for it to be registered as one backslash character. 

En este ejemplo se establecerá el destino de un acceso directo en el escritorio llamado "prueba de acceso directo" a un acceso directo que abre el administrador de archivos en el directorio raíz del disco duro (C:)

+0

Estaba buscando una forma de 'SetWorkingDirectory' a" "para obtener atajos para que funcionen como los programas normales. Esto me ayudó. –

0

La respuesta anterior es perfectamente válida; sin embargo, para completarla realmente, agregué el código para la edición masiva porque supongo que es posible que tenga muchos enlaces para editar.

uso esto si desea editar muchos enlaces a la vez:

import os, sys 
import glob 
import pythoncom 
from win32com.shell import shell, shellcon 

def shortcut_target (filename): 
    link = pythoncom.CoCreateInstance (
    shell.CLSID_ShellLink,  
    None, 
    pythoncom.CLSCTX_INPROC_SERVER,  
    shell.IID_IShellLink 
) 
    persist_file = link.QueryInterface (pythoncom.IID_IPersistFile) 
    persist_file.Load (filename) 
    # 
    # GetPath returns the name and a WIN32_FIND_DATA structure 
    # which we're ignoring. The parameter indicates whether 
    # shortname, UNC or the "raw path" are to be 
    # returned. Bizarrely, the docs indicate that the 
    # flags can be combined. 
    # 
    name, _ = link.GetPath (shell.SLGP_UNCPRIORITY) 

    target = name 
    target = target.replace('H:\My Music', 'D:\Users\Myself\My Music') 

    link.SetPath(target) 
    persist_file.Save(filename, 0) 

    return name 

def shell_glob (pattern): 
    for filename in glob.glob (pattern): 
    if filename.endswith (".lnk"): 
     print shortcut_target(filename) 



desktop = "H:\My Music\" 
for filename in shell_glob (os.path.join (desktop, "*")): 
    print filename 
Cuestiones relacionadas