LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

【Python】ショートカットファイル(.lnk)の正式なファイルパスを取得する

Pythonにおいて、Windowsのショートカットファイル(.lnk)ファイルの中身のファイルを呼び出す方法

1. 結論

WSHの組み込みオブジェクトであるWshShortcutをPythonから呼び出して使用する

ここではスタートメニューのメモ帳を例にしている

win_shortcut.py
import win32com.client

notepad_path = "C:\\Users\\{USERNAME}\\AppData\\Roaming\\Microsoft\Windows\Start Menu\\Programs\\Accessories\\Notepad.lnk"

wshell = win32com.client.Dispatch("WScript.Shell") # <COMObject WScript.Shell>
shortcut = wshell.CreateShortcut(notepad_path)

print(shortcut.TargetPath) # C:\WINDOWS\system32\notepad.exe

2. PythonからCOMオブジェクトを呼び出す

pywin32というライブラリを使用する
pipからインストールできる

pip install pywin32

以下のコードでVBScriptでいうWscript.CreateObject("WScript.Shell")のようなCOMオブジェクトの呼び出しができる

import win32com.client

wshell = win32com.client.Dispatch("WScript.Shell") #<COMObject WScript.Shell>

3. WshShortcutオブジェクトを生成してショートカットの情報を取得する

WshShortcutオブジェクトを生成して、TargetPathプロパティを取得する

shortcut = wshell.CreateShortcut(notepad_path)

print(shortcut.TargetPath) # C:\WINDOWS\system32\notepad.exe

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0