如何用Python知道Windows的安装位置?

16 浏览
0 Comments

如何用Python知道Windows的安装位置?

我正在编写一个需要知道哪个是Windows驱动器的程序。因为我需要访问“Windows-驱动器:\\Users\\publick\\Desktop”,我需要一些能够给我Windows驱动器的代码或模块。

谢谢您的善意。

admin 更改状态以发布 2023年5月20日
0
0 Comments

#!/usr/bin/env python3
# Python program to explain os.system() method 
# importing os module 
import os 
# Command to execute
# Using Windows OS command
cmd = 'echo %WINDIR%'
# Using os.system() method
os.system(cmd)        # check if returns the directory [var = os.system(cmd) print(var) ] in Linux it doesnt
# Using os.popen() method
return_value = os.popen(cmd).read()

你能检查这个方法吗?我不在Windows系统上。

0
0 Comments

如果你真正想要的是安装了Windows的驱动器,请使用

import os
windows_drive = os.environ['SystemDrive']

但是看起来,实际上你需要的是公共桌面文件夹。你可以像这样更轻松和可靠地得到它:

import os
desktop_folder = os.path.join(os.environ['PUBLIC'], 'Desktop')

对于当前用户的桌面文件夹,你可以使用以下方法:

import os
desktop_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop')

但我不确定桌面文件夹总是被称为“桌面”,并且它总是概述文件夹的子目录。

使用pywin32包有一种更可靠的方法(https://github.com/mhammond/pywin32),但显然这只在你安装了这个包之后才能工作:

import win32comext.shell.shell as shell
public_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_PublicDesktop)
user_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_Desktop)

(不幸的是,pywin32文件并没有很好地记录。首先是使用Microsoft的Win32 API来解决问题,然后找出在pywin32中的函数在哪里。)

0