QFileDialog.getExistingDirectory()是否识别%USERNAME%?

时间:2015-06-30 12:44:33

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

我正在尝试使用写入.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))

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

2 个答案:

答案 0 :(得分:2)

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

relativeWorkingDir

答案 1 :(得分:0)

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

%USERPROFILE%语法是特定于窗口的引用环境变量的方式。它不会被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')