在python中列出驱动器和网络位置[Windows]

时间:2018-05-25 11:28:59

标签: python windows

问题:

如何在Windows 10下使用Python获取所有驱动器和网络位置的列表?该列表应包含"本地驱动器","网络驱动器"和"网络位置"。

实施例

TYP           HD      HD        NETWORK LOCATION
some_list = ["C:\\", "D:\\", "\\some.network.address\some_folder"]

我的解决方案:

有没有更好的方法来解决问题?我不认为我的快捷方式解析是好的"溶液...

import win32api
from os import getenv, listdir
from os.path import join
import win32com.client

NETWORK_SHORTCUTS_FOLDER_PATH = getenv('APPDATA') + \
                                "\\Microsoft\\Windows\\Network Shortcuts"

# Add Logical Drives
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]

# Add Network Locations
network_shortcuts = [join(NETWORK_SHORTCUTS_FOLDER_PATH, f) +
                     "\\target.lnk" for f in listdir(NETWORK_SHORTCUTS_FOLDER_PATH)]
shell = win32com.client.Dispatch("WScript.Shell")
for network_shortcut in network_shortcuts:
    shortcut = shell.CreateShortCut(network_shortcut)
    drives.append(shortcut.Targetpath)

print(drives)

网络位置(不仅是网络驱动器!):

Windows 10

1 个答案:

答案 0 :(得分:1)

(第一部分是背景信息。滚动到下一个水平线以获取具体建议。)

您实际上在Win10中映射网络驱动器的方式与先前版本相同:How to Map a Network Drive in Windows 10

您在屏幕截图中显示的是映射驱动器,而是“网络快捷方式”。 XP有一个名为“网络位置”的类似功能,它收集了最近访问过的网络共享的自动生成列表 - 与最近打开的文件的最近一样;该文件夹中包含KNOWNFOLDERID FOLDERID_NetHood并在用户个人资料中使用了NetHood文件夹。 This feature was removed in Vista because it proved rather useless。现在,同一KNOWNFOLDERID用于“网络位置”功能基本相同,但列表由手工和/或by domain administrators via Group Policy组成,并且它占用Network Shortcuts文件夹默认值。

Network Locations are apparently being recommended over mapped drives because they are more manageable

请注意,映射驱动器和网络位置均为每用户。

现在,为了使您的代码更健壮,您所需要的只是不依赖于有关位置和格式的“内部知识”,而是尽可能使用提供的API:

相关问题