Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - How to create a shortcut to a folder on Windows?

I have created shortcuts for executables and it works, but when I try to create one for a folder it does not work. It does create a shortcut, it is just not the right 'Target Type'. Please take a look at the image below. Instead of 'File', the target type should be 'File folder'. The problem is that when I open the shortcut it asks me which program do I want to open the File with and it does not open the folder.

screenshot showing incorrect Target property of a shortcut created to a folder with my code

The function I'm using to create the shortcuts is the following

from win32com.client import Dispatch
import winshell
import os

def create_shortcuts(self, tool_name, exe_path, startin, icon_path):

    shell = Dispatch('WScript.Shell')
    shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk')
    shortcut = shell.CreateShortCut(shortcut_file)
    shortcut.Targetpath = exe_path
    shortcut.WorkingDirectory = startin
    shortcut.IconLocation = icon_path
    shortcut.save()

I don't know if it's possible to set the 'Target Type'. I couldn't find a way to do it, but I do know there must be a way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to use .Net "clr" (especially if you already require it):

First run this... you will have to ship the output of this command this with your application

"c:Program Files (x86)Microsoft SDKsWindowsv10.0AinNETFX 4.6.1 ToolsTlbImp.exe" %SystemRoot%system32wshom.ocx /out:Interop.IWshRuntimeLibrary.dll

tlbimp.exe might even be in the path if you installed the Windows SDK in a fairly standard way. But if not, it's OK, you'll just ship the "assembly" (fancy word for interface-providing dll in .Net land) with your application.

Then this code will work in python:

import clr
sys.path.append(DIRECTORY_WHERE_YOU_PUT_THE_DLL)
clr.AddReference('Interop.IWshRuntimeLibrary')
import Interop.IWshRuntimeLibrary
sc = Interop.IWshRuntimeLibrary.WshShell().CreateShortcut("c:\test\sc.lnk")
isc = Interop.IWshRuntimeLibrary.IWshShortcut(sc)
isc.set_TargetPath("C:")
isc.Save()

.... the above code, with far too much modification and preamble, might even work with Mono.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...