LoginSignup
5
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-01-10

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
5
0
1

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
  3. You can use dark theme
What you can do with signing up
5
0