【问题标题】:Does QFileDialog.getExistingDirectory() recognize %USERNAME%?QFileDialog.getExistingDirectory() 是否识别 %USERNAME%?
【发布时间】:2015-06-30 12:44:32
【问题描述】:

我正在尝试打开一个目录对话框,其中包含写入 .ini 文件的默认目录。

.ini 文件如下所示:

defaultWorkingDirectory = "%%USERPROFILE%%\Documents\CAD\Working_Directory"

我写了一个函数来打开目录对话框:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
from os.path import expanduser
import configparser
import itertools
import re

self.home = expanduser("~")
self.defaultPath = self.home + "\Documents\OptCAD\Working_Directory"

def openDirectoryDialog(self):
    cfg = configparser.ConfigParser()
    cfg.read_file(itertools.chain(['[global]'], open('C:\\Program Files (x86)\\CAD\\config.ini')))
    print(cfg.items('global')) # It returns : [('defaultworkingdirectory', '"%USERPROFILE%\\Documents\\OptCAD\\Working_Directory"')]

    cfgList = cfg.items('global')
    wDirTuple = cfgList[(0)]
    _, workingDir = wDirTuple

    print(workingDir) # It returns : "%USERPROFILE%\Documents\OptCAD\Working_Directory"

    self.directoryName = str(QFileDialog.getExistingDirectory(self, "Select Working Directory", workingDir, QFileDialog.ShowDirsOnly))

然后当我打开目录对话框时,默认目录不是好目录。

【问题讨论】:

    标签: python python-3.x pyqt environment-variables pyqt5


    【解决方案1】:

    您总是可以使用expanduser 获取用户配置文件路径,%USERPROFILE% 需要什么?您可以在您的案例Documents\OptCAD\Working_Directory 中将相对路径存储在配置文件中,然后以与变量relativeWorkingDir 相同的方式读取它。最后像这样与用户个人资料一起加入它。

    workingDir = os.path.join(os.path.expanduser('~'), relativeWorkingDir)
    

    【讨论】:

    • 谢谢,它有效!另外,为了操作,我需要删除relativeWorkingDir的双引号,感谢newRelativeWorkingDir = relativeWorkingDir[1:-1]
    【解决方案2】:

    我假设您正在尝试做的是从您无法控制的程序的配置文件中读取值。

    %USERPROFILE% 语法是特定于 Windows 的引用环境变量的方式。它不会被 Python 或 Qt 自动扩展,所以你必须自己做:

    import os
    
    userprofile = os.environ.get('USERPROFILE')
    workingdir = cfg.get('global', 'defaultworkingdirectory', fallback=None)
    
    if workingdir and userprofile:
        workingdir = workingdir.replace('%USERPROFILE%', userprofile)
    else:
        workingdir = os.exanduser('~\Documents\OptCAD\Working_Directory')
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2011-02-21
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多