def read_settings(self):
self.settings = QtCore.QSettings('fume', 'Match-Explorer')
self.resize(self.settings.value('mainwindow/size', self.size()))
try:
self.move(self.settings.value('mainwindow/pos'))
except:
pass
self.actionZeitraum.setChecked(self.settings.value('menubar/date/range', True, bool))
self.actionZeitpunkt.setChecked(self.settings.value('menubar/date/day', False, bool))
now = datetime.datetime.now()
self.dateEdit_3.setDate(self.settings.value('date_from_calendar', QtCore.QDate(now.year, now.month, now.day)))
self.dateEdit_4.setDate(self.settings.value('date_to_calendar', QtCore.QDate(now.year, now.month, now.day)))
# dbPaths
# Windows: ?C:\Users\<User>\AppData\Local\FuME\FuME
# macOS: /Users/<User>/Library/Application Support/FuME
userDataDir = appdirs.user_data_dir('FuME', 'FuME')
src = self.get_pathToTemp(['db', 'sql_default.db'])
dst = os.path.join(userDataDir, 'sql.db')
if not os.path.exists(userDataDir):
os.makedirs(userDataDir)
shutil.copy(src, dst)
self.dbPath = dst
python类user_data_dir()的实例源码
def check_legacy_v2(self):
""" Look for legacy wallet and move to new directory
"""
appname = "steem"
appauthor = "Fabian Schuh"
storageDatabase = "steem.sqlite"
data_dir = user_data_dir(appname, appauthor)
sqlDataBaseFile = os.path.join(data_dir, storageDatabase)
if os.path.isdir(data_dir) and not os.path.exists(self.sqlDataBaseFile):
# Move whole directory
try:
shutil.copytree(data_dir, self.data_dir)
except FileExistsError:
pass
# Copy piston.sql to steem.sql (no deletion!)
shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
log.info("Your settings have been moved to {}".format(self.sqlDataBaseFile))
def load_tasks():
dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl"))
task_file = dest.child("tasks.json")
if not task_file.exists():
dest.makedirs(True)
task_file.setContent(b"[]")
loaded = cattr.loads(
json.loads(task_file.getContent().decode('utf8')),
List[Task])
def sort(x):
time = load_time_spent(x)
return get_time_needed_for_session(x) - get_time_for_session(x, time)
loaded.sort(key=sort, reverse=True)
return loaded
def getDataDirectory(moduleName=None):
"""
Get a data directory for the caller function, or C{moduleName} if given.
@param moduleName: The module name if you don't wish to have the caller's
module.
@type moduleName: L{str}
@returns: A directory for putting data in.
@rtype: L{str}
"""
if not moduleName:
caller = currentframe(1)
moduleName = inspect.getmodule(caller).__name__
return appdirs.user_data_dir(moduleName)
def check_legacy_v2(self):
""" Look for legacy wallet and move to new directory
"""
appname = "steem"
appauthor = "Fabian Schuh"
storageDatabase = "steem.sqlite"
data_dir = user_data_dir(appname, appauthor)
sqlDataBaseFile = os.path.join(data_dir, storageDatabase)
if os.path.isdir(data_dir) and not os.path.exists(self.sqlDataBaseFile):
# Move whole directory
try:
shutil.copytree(data_dir, self.data_dir)
except FileExistsError:
pass
# Copy piston.sql to steem.sql (no deletion!)
shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
log.info("Your settings have been moved to {}".format(self.sqlDataBaseFile))
def __init__(self):
self._options_stack = [ default_pyomo_config() ]
# Load the user's configuration
sources = [(json.load, 'json')]
if yaml_available:
sources.append( (yaml.load, 'yml') )
sources.append( (yaml.load, 'yaml') )
for parser, suffix in sources:
cfg_file = os.path.join( appdirs.user_data_dir('pyomo'),
'config.'+suffix)
if os.path.exists(cfg_file):
fp = open(cfg_file)
try:
data = parser(fp)
except:
logger.error("Error parsing the user's default "
"configuration file\n\t%s." % (cfg_file,))
self._options_stack[0].set_value(data)
test_freeze_update_available.py 文件源码
项目:pyupdater-wx-demo
作者: wettenhj
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def tearDown(self):
"""
Clean up.
"""
wxupdatedemo.__version__ = self.originalVersion
try:
shutil.rmtree(self.tempDir)
except OSError:
logger.warning("Couldn't remove %s", self.tempDir)
os.chdir(self.initialWorkingDir)
try:
shutil.rmtree(self.fileServerDir)
except OSError:
logger.warning("Couldn't remove %s", self.fileServerDir)
del os.environ['PYUPDATER_FILESERVER_DIR']
del os.environ['WXUPDATEDEMO_TESTING']
del os.environ['WXUPDATEDEMO_TESTING_FROZEN']
del os.environ['WXUPDATEDEMO_TESTING_APP_NAME']
del os.environ['WXUPDATEDEMO_TESTING_COMPANY_NAME']
del os.environ['WXUPDATEDEMO_TESTING_APP_VERSION']
del os.environ['WXUPDATEDEMO_TESTING_PUBLIC_KEY']
if os.path.exists(appdirs.user_data_dir(APP_NAME, COMPANY_NAME)):
try:
shutil.rmtree(appdirs.user_data_dir(APP_NAME, COMPANY_NAME))
except OSError:
logger.warning("Couldn't remove %s",
appdirs.user_data_dir(APP_NAME, COMPANY_NAME))
def get_base_directory():
"""Return base directory where cache and output data are saved.
Creates directory if it is not already present."""
return create_dir(appdirs.user_data_dir("Wurst", "WurstTeam"))
def __init__(self, path=None):
self.path = path or os.path.join(
appdirs.user_data_dir(CONFIG_APPNAME), DB_NAME)
db_dir = os.path.dirname(self.path)
if not os.path.exists(db_dir):
os.makedirs(db_dir)
self.db = lmdb.open(self.path)
# XXX removal when expired? Indexing by time?
def pytest_runtest_teardown(item, nextitem):
path = os.path.join(
appdirs.user_data_dir(nkms.db.CONFIG_APPNAME), nkms.db.DB_NAME)
if os.path.exists(path):
shutil.rmtree(path)
def configure_argparser(self):
a = self.argparser
a.add_argument(
"-c", "--cache-directory", type=str, default=str(CurseForgeClient.DEFAULT_CACHE_DIR),
help="Path to directory to cache mccdl files. Defaults to %(default)s."
)
a.add_argument(
"-l", "--log-level", type=str, default="info",
choices=("debug", "info", "warning", "error", "critical"),
help="Log level to use for this run. Defaults to %(default)s."
)
a.add_argument(
"--upgrade", action="store_true", default=False,
help="If specified, allow upgrading an existing modpack instance."
)
a.add_argument(
"--multimc-directory", type=str, default=appdirs.user_data_dir("multimc5"),
help="Path to the MultiMC directory. Defaults to %(default)s."
)
a.add_argument(
"modpack_url", type=str,
help="Link to the modpack on Minecraft CurseForge."
)
a.add_argument(
"instance_name", type=str,
help="Name of the MultiMC instance to create."
)
def get_data_dir():
"""Return path to the data directory."""
# Use data_dir config value if set, otherwise use OS-dependent data directory given by appdirs
return config.get('data_dir', appdirs.user_data_dir('ChemDataExtractor'))
def deleteDatabase(self):
appdir = appdirs.user_data_dir('FuME', 'FuME')
ret = QtWidgets.QMessageBox.critical(self, QtWidgets.qApp.tr("Datenbank löschen"),
QtWidgets.qApp.tr("Willst du wirklich die Datenbank von FuME löschen? "
"Alle importierten Spiele gehen verloren.\n\n"
"Drücke OK um zu bestätigen und Abbrechen um zurückzukehren."),
QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
if ret == QtWidgets.QMessageBox.Ok:
QtWidgets.QMessageBox.critical(self, QtWidgets.qApp.tr("Datenbank löschen"),
QtWidgets.qApp.tr("Die Datenbank wird gelöscht und das Programm beendet.\n\n"
"Nach dem Beenden sind alle Spiele entfernt."),
QtWidgets.QMessageBox.Ok)
self.parent().close()
shutil.rmtree(appdir)
def link_to_qutebrowser_userscripts_directory(path, name):
import appdirs
appdir = appdirs.user_data_dir('qutebrowser', 'qutebrowser')
userscripts_dir = os.path.join(appdir, 'userscripts')
userscripts_path = os.path.join(userscripts_dir, name)
interpreter = get_interpreter()
if not os.path.exists(userscripts_dir):
os.makedirs(userscripts_dir, exist_ok=False)
with open(userscripts_path, 'w') as bin_file:
bin_file.write(LOADER_TEMPLATE.format(
interpreter=interpreter,
path=path,
))
setup_permissions(userscripts_path)
return userscripts_path
def check_legacy_v1(self):
""" Look for legacy wallet and move to new directory
"""
appname = "piston"
appauthor = "Fabian Schuh"
storageDatabase = "piston.sqlite"
data_dir = user_data_dir(appname, appauthor)
sqlDataBaseFile = os.path.join(data_dir, storageDatabase)
if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
# Move whole directory
shutil.copytree(data_dir, self.data_dir)
# Copy piston.sql to steem.sql (no deletion!)
shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
log.info("Your settings have been moved to {}".format(self.data_dir))
def check_legacy_v1(self):
""" Look for legacy wallet and move to new directory
"""
appname = "piston"
appauthor = "Fabian Schuh"
storageDatabase = "piston.sqlite"
data_dir = user_data_dir(appname, appauthor)
sqlDataBaseFile = os.path.join(data_dir, storageDatabase)
if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
# Move whole directory
shutil.copytree(data_dir, self.data_dir)
# Copy piston.sql to steem.sql (no deletion!)
shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
log.info("Your settings have been moved to {}".format(self.data_dir))
def load_time_spent(task):
dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl")).child("time")
dest.makedirs(True)
task_time_file = dest.child(str(task.id) + ".json")
if not task_time_file.exists():
dest.makedirs(True)
task_time_file.setContent(b"[]")
return cattr.loads(
json.loads(task_time_file.getContent().decode('utf8')),
List[TimeSpent])
def save_time_spent(task, time):
dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl")).child("time")
dest.makedirs(True)
task_time_file = dest.child(str(task.id) + ".json")
task_time_file.setContent(json.dumps(cattr.dumps(time)).encode('utf8'))
def save_tasks(tasks):
dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl"))
dest.makedirs(True)
task_file = dest.child("tasks.json")
task_file.setContent(json.dumps(cattr.dumps(tasks)).encode('utf8'))
def resolve_projector(projector):
password = None
# host:port
if projector is not None and ':' in projector:
host, port = projector.rsplit(':', 1)
port = int(port)
# maybe defined in config
else:
appdir = appdirs.user_data_dir('pjlink')
conf_file = path.join(appdir, 'pjlink.conf')
try:
config = ConfigParser({'port': '4352', 'password': ''})
with open(conf_file, 'r') as f:
config.readfp(f)
section = projector
if projector is None:
section = 'default'
host = config.get(section, 'host')
port = config.getint(section, 'port')
password = config.get(section, 'password') or None
except (NoSectionError, IOError):
if projector is None:
raise KeyError('No default projector defined in %s' % conf_file)
# no config file, or no projector defined for this host
# thus, treat the projector as a hostname w/o port
host = projector
port = 4352
return host, port, password
def data_dir():
return user_data_dir(app_name, app_author)
def get_filepath(cluster, env, is_refresh=False):
app_dir = user_data_dir('envmgr', 'trainline')
filename = 'patch_{0}_{1}'.format(cluster.lower(), env.lower())
if is_refresh:
filename += '_refresh'
filename = '{0}.json'.format(sha1(filename.encode('utf-8')).hexdigest())
return os.path.join(app_dir, filename)
def get_user_dir(dir_type):
dir_path = None
if dir_type == 'config':
dir_path = user_config_dir(appname='fdeunlock')
elif dir_type == 'data':
dir_path = user_data_dir(appname='fdeunlock')
else:
raise NotImplementedError
os.makedirs(dir_path, exist_ok=True) # pylint: disable=unexpected-keyword-arg
return dir_path
def __init__(self):
self.app_data_dir = user_data_dir(self.appname)
#print >>sys.stderr, "ConfigStoreJson app_data_dir:", self.app_data_dir
if not os.path.exists(self.app_data_dir):
os.makedirs(self.app_data_dir)
self.config_file = os.path.join(self.app_data_dir, 'config.json')
#print >>sys.stderr, "ConfigStoreJson config_file:", self.config_file
self.setup()
def __init__(self,model_uuid):
self.database = os.path.join(appdirs.user_data_dir(__app__),__filename__)
self.model_uuid = model_uuid
conn = sqlite3.connect(self.database)
conn.row_factory = dict_factory
c = conn.cursor()
sql = "select input_uuid, type, variable_name, elicit_question from inputs where model_uuid=?"
c.execute(sql,[(self.model_uuid)])
metadata = c.fetchall()
if len(metadata)==0:
raise ValueError('The model_uuid provided is not in the database.')
sql = "select name,response, doi, implementation_file from models where model_uuid=?"
c.execute(sql,[(self.model_uuid)])
model = c.fetchall()
self.model_name = model[0].get('name')
self.doi = model[0].get('doi')
self.score_file = model[0].get('implementation_file')
self.response = model[0].get('response')
def __model_input_choices(input_uuid):
sql = "select display_text from choices where input_uuid=?"
c.execute(sql,[(input_uuid)])
results = c.fetchall()
return [x.get('display_text') for x in results]
self.ask = {x.get('elicit_question'): __model_input_choices(x.get('input_uuid')) for x in metadata}
self.parameter_name = [x.get('variable_name') for x in metadata]
self.variable_type = [x.get('type') for x in metadata]
c.close()
conn.close()
def __init__(self):
if not ConfigStore.store:
print "ConfigStoreShelve.__init__"
self.app_data_dir = user_data_dir('kotori', 'elmyra')
if not os.path.exists(self.app_data_dir):
os.makedirs(self.app_data_dir)
self.config_file = os.path.join(self.app_data_dir, 'config')
ConfigStore.store = shelve.open(self.config_file, writeback=True)
def __init__(self):
if not ConfigStoreJson.store:
#print "ConfigStoreJson.__init__"
self.app_data_dir = user_data_dir('kotori-daq', 'Elmyra')
logger.debug("ConfigStoreJson app_data_dir: {}".format(self.app_data_dir))
if not os.path.exists(self.app_data_dir):
os.makedirs(self.app_data_dir)
self.config_file = os.path.join(self.app_data_dir, 'config.json')
ConfigStoreJson.store = json_store.open(self.config_file)
def default_storage_dir(self):
udd = user_data_dir('python-for-android')
if ' ' in udd:
udd = '~/.python-for-android'
return udd
def get_appdirs_path(subdir):
"""Get path for an ``appdirs`` directory, with subdirectory ``subdir``.
Returns the full directory path."""
dirpath = os.path.join(
appdirs.user_data_dir("pandarus", "pandarus-cache"),
subdir
)
if not os.path.isdir(dirpath):
os.makedirs(dirpath)
return os.path.abspath(dirpath)
def check_legacy_v1(self):
""" Look for legacy wallet and move to new directory
"""
appname = "piston"
appauthor = "Fabian Schuh"
storageDatabase = "piston.sqlite"
data_dir = user_data_dir(appname, appauthor)
sqlDataBaseFile = os.path.join(data_dir, storageDatabase)
if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
# Move whole directory
shutil.copytree(data_dir, self.data_dir)
# Copy piston.sql to steem.sql (no deletion!)
shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
log.info("Your settings have been moved to {}".format(self.data_dir))