示例#1
0
文件: config.py 项目: wthys/pydof
    def write(self, filename=None):
        """
		Writes a configuration file.

		Write a configuration file at <pre>filename</pre>. If no filename 
		is supplied, the default path is <pre>~/.config/pydof/pydof.rc</pre> 
		or the <pre>pydof/pydof.rc</pre> file in your configured XDG
		configuration directory.
		"""
        if filename is None:
            basedir.save_config_path("pydof")
            self.write(Config.DEFAULTPATH)
        else:
            with open(filename, "w") as configfile:
                self.__parser.write(configfile)
示例#2
0
    def __init__(self, release):
        self.release = release
        self.name = 'apt-venv'
        self.config = _loadJSON(open('/etc/apt-venv.conf'))

        self.distro = None
        for distro in self.config['distributions']:
            if self.release in self.config['distributions'][distro]['releases']:
                self.distro = distro
        if not self.distro:
            base = "Release \"{}\" not valid. ".format(self.release)
            if not self.release:
                base = "No release declared. "
            all_releases = []
            for distro in sorted(self.config['distributions'].keys()):
                releases = self.config['distributions'][distro]['releases']
                all_releases.append(" [%s] %s" % (distro, ' - '.join(releases)))
            raise ValueError(base +
                             "Please specify one of:\n%s" %
                             '\n'.join(all_releases))
        self.config_path = _BaseDirectory.save_config_path(self.name)
        self.cache_path = _BaseDirectory.save_cache_path(self.name)
        self.data_path = _BaseDirectory.save_data_path(self.name)
        self.config_path = _os.path.join(self.config_path, self.release)
        self.cache_path = _os.path.join(self.cache_path, self.release)
        self.data_path = _os.path.join(self.data_path, self.release)

        self.bashrc = _os.path.join(self.config_path, "bash.rc")
        self.sourceslist = _os.path.join(self.config_path, "sources.list")
        self.aptconf = _os.path.join(self.config_path, "apt.conf")
示例#3
0
def read_config(args):
    config = os.path.join(xdg.save_config_path(myname), "%s.conf" % myname)

    username = ""
    password = ""
    hostnames = []

    # Read
    log.debug("Reading settings from '%s'", config)
    try:
        with open(config, 'r') as fd:
            username, password = fd.readline().strip().split('\t')
            for line in fd:
                hostnames.append(line.strip())
    except IOError as e:
        log.warn(e)
    except ValueError as e:
        log.error("Error in config file, check credentials at '%s'", config)

    # Save
    if args.username or args.password or args.hostnames:
        log.info("Saving settings to '%s'", config)
        try:
            with open(config, 'w') as fd:
                fd.write("%s\t%s\n" % (args.username or username,
                                       args.password or password,))
                for hostname in (args.hostnames or hostnames):
                    fd.write("%s\n" % hostname)
            os.chmod(config, 0600)
        except IOError as e:
            log.error(e)

    return dict(username=username,
                password=password,
                hostnames=hostnames)
示例#4
0
文件: util.py 项目: mikewaters/hobo
    def __init__(self):
        config_dir = xdg.save_config_path('hobo')
        data_dir = xdg.save_data_path('hobo')
        self.images_dir = os.path.join(data_dir, 'images')

        if not os.path.isdir(self.images_dir):
            os.mkdir(self.images_dir)

        self.template_file = os.path.join(self.images_dir, 'hobo.templates')
        touch(self.template_file)

        self.db = Db(os.path.join(data_dir, 'hobo.db'))

        config_file = os.path.join(config_dir, 'hobo.ini')
        self._cfg = ConfigParser()
        self._cfg.read(config_file)

        self.bridge_device = self.get('config', 'bridge_device') or 'hob0'
        self.base_mem = self.get('config', 'base_mem') or '1024'
        self.base_cpu = self.get('config', 'base_cpu') or '1'

        # compression analysis:
        #  -1 256M
        #  -9 213M
        #  --best 223M
        # might as well use -1
        # libvirt docs recommend:
        #   --best --block-size=16777216
        # but it's sloooow
        self.compress_flags = self.get('config', 'compress_flags') or '-1 -T0 --block-size=16777216'
示例#5
0
def get_auth():
    def check_auth(auth):
        return requests.head(full_repo_url, auth=auth).status_code != httplib.UNAUTHORIZED

    # config file init
    config_file = os.path.join(BaseDirectory.save_config_path("malucrawl_reportificate"), "settings.ini")
    config = configparser.SafeConfigParser()
    config.read(config_file)

    if not config.has_section('auth'):
        config.add_section('auth')

    try:
        username = config.get('auth', 'username')
    except configparser.NoOptionError:
        username = raw_input("Username: "******"Authorization Failed"
        username = raw_input("Username: ")
        password = getpass.getpass()

    keyring.set_password(github_url, username, password)
    config.set('auth', 'username', username)
    config.write(open(config_file, 'w'))

    return (username, password)
示例#6
0
文件: nag.py 项目: johnw42/nag
  def __init__(self):
    self.key_sequence = KeySequence()
    self.nag_interval = 300
    self.nag_header = '\nReminders:'
    self.use_git = True

    os.environ.pop('GIT_DIR', None)

    # for path in xdgbase.load_config_paths(APP_NAME, 'config.py'):
    #   with file(path) as stream:
    #     exec stream in self.__dict__

    self.nag_home = xdgbase.save_config_path(APP_NAME)
    self.nag_file_dir = xdgbase.save_config_path(APP_NAME, 'files')
    self.runtime = os.path.join(xdgbase.get_runtime_dir(), APP_NAME)
    self.timestamp = os.path.join(self.runtime, 'timestamp')
示例#7
0
  def __init__(self):
    self.palette = None
    self.color = Color()
    self.color.connect('changed', self.color_changed)

    self.icon_path = os.path.join(os.path.dirname(__file__), 'data', 'icons')

    self.init_config()
    self.build_gui()

    self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), 'palettes')
    Palette.PaletteDir = self.palette_dir

    self.palette_list = PaletteList()
    self.palette_list.load(self.palette_dir)
    self.palette_combo.set_model(self.palette_list)

    # no palettes, so create default
    if len(self.palette_list) == 0:
      palette = Palette()
      palette.name = "Default Palette"
      palette.filename = os.path.join(self.palette_dir, 'default.gpl')
      self.palette_list.append(palette)

      self.palette_combo.select(0)

    self.colorpicker.set_color(self.color)

    self.load_config()
示例#8
0
    def __init__(self, sender=None, addresses=[], *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not isinstance(addresses, list):
            addresses = [addresses]
        elif not addresses:
            import xdg.BaseDirectory as xdgb

            p = xdgb.load_first_config('notifier', 'addresses')
            if p is not None:
                with open(p, 'r') as f:
                    addresses = f.read().split()
            if not addresses:
                raise ValueError('No email addresses (defaults are read from {}/addresses, one address per line)'
                                 .format(xdgb.save_config_path('notifier')))
        for addr in addresses:
            if not isinstance(addr, str) or not '@' in addr:
                raise TypeError('`addresses` must be an email address or a list of email addresses')
        self._addresses = addresses

        if sender is None:
            sender = 'Notifier'
        self._sender = sender

        self._addr = 'notifier@{}'.format(platform.node())
示例#9
0
    def __init__(self):
        self.palette = None
        self.color = Color()
        self.h_ids = {}
        self.color.connect("changed", self.color_changed)

        self.init_config()
        self.build_gui()

        self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), "palettes")
        Palette.PaletteDir = self.palette_dir

        self.palette_list = PaletteList()
        self.palette_list.load(self.palette_dir)
        self.palette_combo.set_model(self.palette_list)

        # no palettes, so create default
        if len(self.palette_list) == 0:
            palette = Palette()
            palette.name = "Default Palette"
            palette.filename = os.path.join(self.palette_dir, "default.gpl")
            self.palette_list.append(palette)

            self.palette_combo.select(0)

        self.colorpicker.set_color(self.color)

        self.load_config()
示例#10
0
	def on_checkautostart_toggled(self, widget):
		KUPFER_DESKTOP = "kupfer.desktop"
		AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
		autostart_dir = base.save_config_path("autostart")
		autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
		if not os.path.exists(autostart_file):
			desktop_files = list(base.load_data_paths("applications",
				KUPFER_DESKTOP))
			if not desktop_files:
				self.output_error("Installed kupfer desktop file not found!")
				return
			desktop_file_path = desktop_files[0]
			# Read installed file and modify it
			dfile = desktop.DesktopEntry(desktop_file_path)
			executable = dfile.getExec()
			## append no-splash
			if "--no-splash" not in executable:
				executable += " --no-splash"
			dfile.set("Exec", executable)
		else:
			dfile = desktop.DesktopEntry(autostart_file)
		activestr = str(bool(widget.get_active())).lower()
		self.output_debug("Setting autostart to", activestr)
		dfile.set(AUTOSTART_KEY, activestr)
		## remove the format specifiers
		executable = dfile.getExec().replace("%F", "")
		dfile.set("Exec", executable)
		dfile.write(filename=autostart_file)
示例#11
0
    def _load_config(self):
        config = ConfigParser.SafeConfigParser()
        self.VERBOSE = False

        self._read_configs_into(config)

        DEFAULT_WORDPRESS_URL = 'http://wordpress.example.com/wordpress/xmlrpc.php'

        if not config.has_section('account'):
            config.add_section('account')
            # Fill in some default values
            config.set('account', 'url', DEFAULT_WORDPRESS_URL)
            config.set('account', 'username', 'joe_user')
            config.set('account', 'password', 'trustNo1')

            config.add_section('config')
            config.set('config', 'data_storage', 'file')
            config.set('config', 'publish_default', 'no')
            config.set('config', 'save_uploads', 'no')
            config.set('config', 'scale_images', 'no')

            path = os.path.join(BaseDirectory.save_config_path('rst2wp'), 'wordpressrc')
            print 'Need configuration! Edit %s'%(path,)
            with file(path, 'wb') as fp:
                config.write(fp)
            sys.exit()

        if config.get('account', 'url') == DEFAULT_WORDPRESS_URL:
            # Don't wipe out what they might have configured
            print 'Still needs configuration! Edit %s'%(path,)
            sys.exit()

        self._config = config
        return config
示例#12
0
文件: main.py 项目: glasserc/tuyau
    def write_empty_config(self, config, conffile):
        rootdir = BaseDirectory.save_config_path('tuyau')
        with file(conffile, 'wb') as fp:
            config.write(fp)

        g = GPG(gnupghome=os.path.join(rootdir, 'gnupg'))
        g.list_keys()
示例#13
0
def load_config():
    resource_name = 'yt-bulk-py'

    if not bd.load_first_config(resource_name):
        sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name))

    conf_dir = bd.load_first_config(resource_name)
    conf_file = os.path.join(conf_dir, 'config')

    conf_skel = """# Configuration file for yt-bulk-py

# Account information for the user doing the uploading.
[user]
email = [email protected]
password = secret
"""

    if not os.path.isfile(conf_file):
        with open(conf_file, 'w+b') as f:
            f.write(conf_skel)

    config = ConfigParser.ConfigParser()
    config.read(conf_file)

    if not 'user' in config.sections():
        sys.stderr.write('Error: No [user] section in config file.')
        exit(1)

    if not 'email' in config.options('user') and 'password' in config.options('user'):
        sys.stderr.write('Error: Missing "email" or "password" options in config file.')
        exit(1)
    return (config.get('user', 'email'), config.get('user', 'password'))
示例#14
0
def load_credentials():
    p = xdgb.load_first_config('prisma', 'credentials')
    if p is None:
        exit('Please save your card number and password (each on its own line) in {}/credentials'
              .format(xdgb.save_config_path('prisma')))
    with open(p, 'r') as f:
        t = f.read().split()
        return (t[0], t[1])
示例#15
0
 def test_save_config_path(self):
     tmpdir = tempfile.mkdtemp()
     try:
         environ['XDG_CONFIG_HOME'] = tmpdir
         reload(BaseDirectory)
         configpath = BaseDirectory.save_config_path("foo")
         self.assertEqual(configpath, os.path.join(tmpdir, "foo"))
     finally:
         shutil.rmtree(tmpdir)
示例#16
0
    def get_save_path(cls):
        """Return a path to where a configuration file may be saved.

        Create parent directories if they don't exist.
        """
        return os.path.join(
            BaseDirectory.save_config_path(cls._get_xdg_subdir()),
            cls._get_config_file(),
        )
示例#17
0
文件: config.py 项目: mvo5/snapcraft
    def __init__(self, *, read_only: bool = False) -> None:
        """Initialize an instance of CLIConfig.

        :param bool read_only: if set, attempts to set data will fail.
        """
        self.parser = configparser.ConfigParser()
        self.config_path = os.path.join(
            BaseDirectory.save_config_path("snapcraft"), "cli.cfg"
        )
        self._read_only = read_only
示例#18
0
	def _get_should_autostart(self):
		KUPFER_DESKTOP = "kupfer.desktop"
		AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
		autostart_dir = base.save_config_path("autostart")
		autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
		if not os.path.exists(autostart_file):
			return False
		dfile = desktop.DesktopEntry(autostart_file)
		return (dfile.hasKey(AUTOSTART_KEY) and
				dfile.get(AUTOSTART_KEY, type="boolean"))
示例#19
0
 def getConfig(self):
     try:
         from xdg import BaseDirectory
         directory = BaseDirectory.save_config_path('morituri')
         path = os.path.join(directory, 'morituri.conf')
         self.info('Using XDG, configuration file is %s' % path)
     except ImportError:
         path = os.path.join(os.path.expanduser('~'), '.moriturirc')
         self.info('Not using XDG, configuration file is %s' % path)
     return path
示例#20
0
 def __init__(self):
     self.CACHE_HOME = os.path.join(BaseDirectory.xdg_cache_home, "puding")
     # creating cache home if it doesn't exist
     if not os.path.isdir(self.CACHE_HOME):
         os.makedirs(self.CACHE_HOME)
     self.CONFIG_HOME = BaseDirectory.save_config_path("puding")
     self.CONFIG_FILE = os.path.join(self.CONFIG_HOME, "settings.json")
     self.DATA_HOME = BaseDirectory.save_data_path("puding")
     self.DATA_PATH = map(self.append_app_name, BaseDirectory.xdg_data_dirs)
     self.DEV_HOME = os.path.abspath(os.path.dirname(__file__))
示例#21
0
 def _get_config_paths(self):
     "Get configuration file paths"
     if _xdg_basedirectory:
         paths = list(reversed(list(_xdg_basedirectory.load_config_paths(""))))
         if not paths:  # setup something for a useful log message
             paths.append(_xdg_basedirectory.save_config_path(""))
     else:
         self._log_xdg_import_error()
         paths = [_os_path.expanduser(_os_path.join("~", ".config"))]
     return [_os_path.join(path, "mutt-ldap.cfg") for path in paths]
示例#22
0
    def __init__(self):
        self._app_path = BaseDirectory.save_config_path(APP_NAME)
        self._file = os.path.join(self._app_path, APP_PREFERENCES_FILE)

        self._desktop = desktop_environment()

        self.compartir = None
        self.profile = None

        self._load()
示例#23
0
文件: config.py 项目: chmouel/kupfer
def save_config_file(filename):
	"""
	Return filename in the XDG data home directory, where the
	directory is guaranteed to exist
	"""
	direc = base.save_config_path(PACKAGE_NAME)
	if not direc:
		return None
	filepath = os.path.join(direc, filename)
	return filepath
示例#24
0
 def __init__(self, debug=False):
     homedir = os.path.expanduser('~')
     self._conf_dir_name = BaseDirectory.save_config_path('actracker')
     self._log_dir_name = BaseDirectory.save_data_path('actracker')
     self._conf_fname = os.path.join(self._conf_dir_name, 'conf.json')
     self._load_conf()
     self._load_log()
     self._last_application = ('', '')
     self.activity_counter = {}
     self._current_day = datetime.now().day
     self.debug = debug
示例#25
0
文件: preferences.py 项目: pbx/kupfer
 def _get_should_autostart(self):
     KUPFER_DESKTOP = "kupfer.desktop"
     AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
     autostart_dir = base.save_config_path("autostart")
     autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
     if not os.path.exists(autostart_file):
         return False
     try:
         dfile = desktop.DesktopEntry(autostart_file)
     except xdg_e.ParsingError, exception:
         pretty.print_error(__name__, exception)
         return False
示例#26
0
 def _get_config_paths(self):
     "Get configuration file paths"
     if _xdg_basedirectory:
         paths = list(reversed(list(
             _xdg_basedirectory.load_config_paths(''))))
         if not paths:  # setup something for a useful log message
             paths.append(_xdg_basedirectory.save_config_path(''))
     else:
         self._log_xdg_import_error()
         paths = [_os_path.expanduser(_os_path.join('~', '.mutt'))]
     # return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths]
     return '/home/derek/.mutt/mutt-ldap.cfg'
示例#27
0
def main(args):
    config = read_config(args)
    logger.debug(args)
    recipients = args.recipients or config['recipients']
    if not recipients:
        logger.error("Recipients list is empty. Set them up once using command line arguments")
        return -1

    ipfile = osp.join(xdg.save_config_path(myname), 'ip')

    try:
        logger.debug("Reading previous IP file: %s", ipfile)
        with open(ipfile) as f:
            oldip = f.read().strip()
    except IOError as e:
        logger.warn(e)
        oldip = ""

    try:
        newip = upnp.external_ip()
    except (upnp.UpnpError, upnp.socket.error) as e:
        logger.error(e)
        return

    if newip == oldip:
        logger.info("IP is still %s", oldip)
        if not args.force:
            return
    elif newip == '0.0.0.0':
        logger.info("IP changed to %s, ignoring", newip)
        if not args.force:
            return
    else:
        logger.info("IP changed from %s to %s", oldip, newip)
        logger.debug("Saving new IP file", ipfile)
        try:
            with open(ipfile, 'w') as f:
                f.write('%s\n' % newip)
        except IOError as e:
            logger.error(e)

    try:
        logger.info("Sending email")
        sendmail.sendmail(myname,
                          recipients,
                          "External public IP changed to %s" % newip,
                          newip,
                          debug=args.debug,)
    except (sendmail.smtplib.SMTPException, sendmail.socket.gaierror) as e:
        logger.error(e)

    logger.info("Notifying NoIP.com")
    noip.main(["-v"] if args.debug else [])
示例#28
0
 def init_config(self):
     # initialize configuration stuff
     path = BaseDirectory.save_config_path('oscopy')
     self.config_file = os.path.join(path, 'gui')
     self.hist_file = os.path.join(path, 'history')
     section = IOscopyApp.SECTION
     self.config = configparser.RawConfigParser()
     self.config.add_section(section)
     # defaults
     self.config.set(section, IOscopyApp.OPT_NETLISTER_COMMANDS, '')
     self.config.set(section, IOscopyApp.OPT_SIMULATOR_COMMANDS, '')
     self.config.set(section, IOscopyApp.OPT_RUN_DIRECTORY, '.')
示例#29
0
文件: main.py 项目: glasserc/tuyau
    def go(self):
        parser = self.make_argument_parser()
        opts = parser.parse_args()

        config = self.get_config(opts)
        if not config: return

        rootdir = BaseDirectory.save_config_path('tuyau')
        app = Application(config.get('general', 'instance_name'),
                          config.get('general', 'couch_url'),
                          gpg_keyring=os.path.join(rootdir, 'gnupg'))

        opts.func(app, opts)
 def read(self):
     """Read the configuration from a file."""
     #Determine where is stored the configuration
     config_file = os.path.join(os.environ.get("HOME"), ".%s" % __appname__)
     if not os.path.isfile(config_file):
         try:
             from xdg import BaseDirectory
         except ImportError:
             pass
         else:
             config_file = os.path.join(
                 BaseDirectory.save_config_path(__appname__), "config.ini")
     if os.path.isfile(config_file):
         self._confp.read([config_file])
示例#31
0
    from xdg import BaseDirectory
except ImportError:
    BaseDirectory = None


PROGRAMNAME = 'pter'
QTPROGRAMNAME = 'qpter'
HERE = pathlib.Path(os.path.abspath(__file__)).parent
HOME = pathlib.Path.home()
CONFIGDIR = HOME / ".config" / PROGRAMNAME
CONFIGFILE = HOME / ".config" / PROGRAMNAME / (PROGRAMNAME + ".conf")
CACHEDIR = HOME / ".cache" / PROGRAMNAME
CACHEFILE = CACHEDIR / (PROGRAMNAME + ".settings")

if BaseDirectory is not None:
    CONFIGDIR = pathlib.Path(BaseDirectory.save_config_path(PROGRAMNAME) or CONFIGDIR)
    CONFIGFILE = CONFIGDIR / (PROGRAMNAME + ".conf")
    CACHEDIR = pathlib.Path(BaseDirectory.save_cache_path(PROGRAMNAME) or CACHEDIR)
    CACHEFILE = CACHEDIR / (PROGRAMNAME + ".settings")

SEARCHES_FILE = CONFIGDIR / "searches.txt"

URL_RE = re.compile(r'([A-Za-z][A-Za-z0-9+\-.]*)://([^ ]+)')

DEFAULT_TASK_FORMAT = '{selection: >} {nr: >} {done} {tracking }{due }{(pri) }{description}'
ATTR_TRACKING = 'tracking'
ATTR_T = 't'
ATTR_DUE = 'due'
ATTR_PRI = 'pri'
ATTR_ID = 'id'
"""Build or update a collection from raw surveys data/"""

import argparse
import ConfigParser
import datetime
import logging
import os
import pkg_resources
import shutil
import sys
from xdg import BaseDirectory

from openfisca_survey_manager.survey_collections import SurveyCollection
from openfisca_survey_manager.surveys import Survey

config_files_directory = BaseDirectory.save_config_path(
    'openfisca-survey-manager')

app_name = os.path.splitext(os.path.basename(__file__))[0]
log = logging.getLogger(app_name)


def add_survey_to_collection(survey_name=None,
                             survey_collection=None,
                             sas_files=[],
                             stata_files=[]):
    assert survey_collection is not None
    overwrite = True
    label = survey_name

    for test_survey in survey_collection.surveys:
        if test_survey.name == survey_name:
示例#33
0
pygame.display.set_icon(icona)

#creo il serpente
snake = pygame.Surface(
    (14, 14))  #creo un quadrato (14x14) snake che sara' il corpo del serpente
snake_testa = pygame.Surface(
    (14, 14)
)  #snake_testa e' la testa del serpente, la differenzio dal corpo per potergli assegnare un colore diverso
snake.fill(VERDE_SCURO)  #coloro di verde scuro il corpo del serpente
snake_testa.fill(VERDE)  #coloro di verde chiaro la testa del serpente

OS = platform.system()  #guardo il sistema operativo

if OS == "Linux":
    from xdg import BaseDirectory
    path_data = BaseDirectory.save_config_path(
        'snake_pygame/')  #imposto il path per il file del record

    #se la cartella del gioco contenente il record non esiste la creo e creo anche il file record.txt impostando il record a 0
    if not os.path.exists(path_data):
        #la cartella non esiste
        os.mkdir(path_data)  #creo la cartella

elif OS == "Windows":
    path_data = os.path.expanduser("~\\") + "snake_pygame\\"

    if not os.path.exists(path_data):
        #la cartella non esiste
        os.mkdir(path_data)

else:  #per gli altri sistemi operativi crea la cartella record all'interno della cartella di gioco
    path_data = ("Record/")
示例#34
0
 def default_config_file_path(self):
     """Build the default config file path."""
     return os.path.join(
         BaseDirectory.save_config_path(self._xdg_config_dir),
         self._xdg_config_file)
示例#35
0
import os
import atexit

from xdg import BaseDirectory

from .config_manager import ConfigurationManager

# Global configuration manager instance
fc = BaseDirectory.save_config_path('angr-management')
if fc is not None:
    config_path = os.path.join(fc, 'config')
    try:
        Conf = ConfigurationManager.parse_file(config_path)
    except FileNotFoundError:
        Conf = ConfigurationManager()
else:
    config_path = None
    print(
        "Could not find configuration directory - settings will not be saved")
    Conf = ConfigurationManager()


def save_config():
    if fc is None:
        return
    Conf.save_file(config_path)


APP_LOCATION = str(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
PLUGIN_PATH = str(os.path.join(APP_LOCATION, 'plugins'))
示例#36
0
def get_config_path(file: str) -> str:
    return str(
        Path(BaseDirectory.save_config_path(APP_PACKAGE_NAME)).joinpath(file))
示例#37
0
 def __init__(self):
     self._config = configparser.RawConfigParser()
     self._config.read(
         os.path.join(BaseDirectory.save_config_path('sbackup'),
                      'settings.conf'))
示例#38
0
MISSING_ICON_NAME = 'application-x-executable'

# Paths constants
# If there's a file data/gnome-appfolders-manager.png then the shared data
# are searched in relative paths, else the standard paths are used
if os.path.isfile(os.path.join('data', 'gnome-appfolders-manager.png')):
    DIR_PREFIX = '.'
    DIR_LOCALE = os.path.join(DIR_PREFIX, 'locale')
    DIR_DOCS = os.path.join(DIR_PREFIX, 'doc')
else:
    DIR_PREFIX = os.path.join(sys.prefix, 'share', 'gnome-appfolders-manager')
    DIR_LOCALE = os.path.join(sys.prefix, 'share', 'locale')
    DIR_DOCS = os.path.join(sys.prefix, 'share', 'doc',
                            'gnome-appfolders-manager')
# Set the paths for the folders
DIR_DATA = os.path.join(DIR_PREFIX, 'data')
DIR_UI = os.path.join(DIR_PREFIX, 'ui')
DIR_SETTINGS = BaseDirectory.save_config_path(DOMAIN_NAME)
# Set the paths for the data files
FILE_ICON = os.path.join(DIR_DATA, 'gnome-appfolders-manager.png')
FILE_CONTRIBUTORS = os.path.join(DIR_DOCS, 'contributors')
FILE_TRANSLATORS = os.path.join(DIR_DOCS, 'translators')
FILE_LICENSE = os.path.join(DIR_DOCS, 'license')
FILE_RESOURCES = os.path.join(DIR_DOCS, 'resources')
# Set the paths for configuration files
FILE_SETTINGS = os.path.join(DIR_SETTINGS, 'settings.conf')
FILE_WINDOWS_POSITION = os.path.join(DIR_SETTINGS, 'windows.conf')
# Settings schema and paths
SCHEMA_FOLDERS = 'org.gnome.desktop.app-folders'
SCHEMA_FOLDER = '%s.folder' % SCHEMA_FOLDERS
示例#39
0
 def _get_config_path(self) -> pathlib.Path:
     return (pathlib.Path(BaseDirectory.save_config_path("snapcraft")) /
             "snapcraft.cfg")
示例#40
0
文件: config.py 项目: einaru/curry
    ~~~~~

    Configuration

    Copyright: (c) 2014 Einar Uvsløkk
    License: GNU General Public License (GPL) version 3 or later
"""
import os
import logging
import configparser

from curry import prog_name

try:
    from xdg import BaseDirectory
    config_path = BaseDirectory.save_config_path(prog_name)
    cache_path = BaseDirectory.save_cache_path(prog_name)
except:
    config_path = os.path.join(os.path.expanduser('~/.config'), prog_name)
    if not os.path.isdir(config_path):
        os.makedirs(config_path)
    cache_path = os.path.join(os.path.expanduser('~/.cache'), prog_name)
    if not os.path.isdir(cache_path):
        os.makedirs(cache_path)

__all__ = ['config', 'get_cache_file']

config_file = os.path.join(config_path, 'config.ini')

log = logging.getLogger(__name__)
示例#41
0
文件: config.py 项目: sebix/tomate
 def get_config_path(self):
     BaseDirectory.save_config_path(self.APP_NAME)
     return os.path.join(
         BaseDirectory.xdg_config_home, self.APP_NAME, self.APP_NAME + ".conf"
     )
示例#42
0
    group.add_argument(
        '-m',
        '--method',
        dest='method',
        choices=['custom', 'deb', 'apt', 'mojo', 'air', 'steam'],
        help="Use this method instead of the default"
        " for (un-)installing a game")

    args = parser.parse_args(argv)
    args.debug = args.loglevel == 'debug'
    return args, parser


if __name__ == '__main__':
    APPNAME = osp.basename(osp.splitext(__file__)[0])
    CONFIGDIR = xdg.save_config_path(APPNAME)  # creates the dir
    CACHEDIR = osp.join(xdg.xdg_cache_home, APPNAME)
    # No changes in DATADIR

    try:
        sys.exit(main())

    except KeyboardInterrupt:
        pass
    except HumbleBundleError as e:
        log.critical(e)
        sys.exit(1)
    except Exception as e:
        log.critical(e, exc_info=True)
        sys.exit(1)
示例#43
0
文件: config.py 项目: jonas/snapcraft
 def save_path() -> str:
     return os.path.join(BaseDirectory.save_config_path('snapcraft'),
                         'snapcraft.cfg')
示例#44
0
import json
import os
import uuid

from gi.repository import GObject
from xdg import BaseDirectory

import keyring

from rsr.connections.backends import get_available_drivers
from rsr.connections.connection import Connection

CONNECTIONS_FILE = os.path.join(BaseDirectory.save_config_path('runsqlrun'),
                                'connections.json')


class ConnectionManager(GObject.GObject):

    __gsignals__ = {
        'connection-deleted': (GObject.SIGNAL_RUN_LAST, None, (str, )),
    }

    def __init__(self, app):
        super(ConnectionManager, self).__init__()
        self.app = app
        self._connections = {}
        self.update_connections()

    def update_connections(self):
        if not os.path.exists(CONNECTIONS_FILE):
            return
示例#45
0
import json
import os

from xdg import BaseDirectory

CONFIG_FILE = os.path.join(BaseDirectory.save_config_path('runsqlrun'),
                           'config.json')


def load():
    if not os.path.exists(CONFIG_FILE):
        return {}
    with open(CONFIG_FILE) as f:
        data = json.load(f)
    return data


def save(data):
    with open(CONFIG_FILE, 'w') as f:
        json.dump(data, f)
示例#46
0
def config():
    return BaseDirectory.save_config_path(_XDG_RESOURCE)
示例#47
0
    DATA_DIR = os.path.join(PREFIX, 'share/crunchyfrog/')
    LOCALE_DIR = os.path.join(PREFIX, 'share/locale/')
    MANUAL_URL = '/usr/share/doc/crunchyfrog/manual/'

if not sys.platform.startswith('win'):
    MANUAL_URL = urlparse.urlunsplit(('file', '', MANUAL_URL, '', ''))

DATA_DIR = os.path.abspath(DATA_DIR)
LOCALE_DIR = os.path.abspath(LOCALE_DIR)


PLUGIN_DIR = os.path.join(DATA_DIR, "plugins")

if not sys.platform.startswith('win'):
    from xdg import BaseDirectory as base_dir
    USER_CONFIG_DIR = base_dir.save_config_path('crunchyfrog')
    USER_DIR = base_dir.save_data_path('crunchyfrog')
else:
    USER_CONFIG_DIR = os.path.abspath(
        os.path.expanduser('~/crunchyfrog/config/'))
    USER_DIR = os.path.abspath(
        os.path.expanduser('~/crunchyfrog/data'))

USER_CONF = os.path.join(USER_CONFIG_DIR, "config")

if not os.path.isdir(USER_CONFIG_DIR):
    os.makedirs(USER_CONFIG_DIR)

if not os.path.isdir(USER_DIR):
    os.makedirs(USER_DIR)
示例#48
0
 def save_path() -> str:
     return os.path.join(BaseDirectory.save_config_path("snapcraft"),
                         "snapcraft.cfg")
示例#49
0
文件: config.py 项目: eamanu/cligh
def get_config_dir():
    """Return the name of the directory containing the application's config file."""
    config_dir = BaseDirectory.load_first_config('cligh')
    if config_dir is None:
        config_dir = BaseDirectory.save_config_path('cligh')
    return config_dir
示例#50
0
from xdg import BaseDirectory

import dnfdaemon.client

from yumex.misc import _, ngettext, CONFIG
import yumex.misc as misc

LOG_ROOT = 'yumex.updater'

logger = logging.getLogger(LOG_ROOT)

BIN_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))

YUMEX_BIN = '/usr/bin/yumex-dnf'

CONF_DIR = BaseDirectory.save_config_path('yumex-dnf')
TIMESTAMP_FILE = os.path.join(CONF_DIR, 'update_timestamp.conf')
DELAYED_START = 5 * 60  # Seconds before first check


class _Notification(GObject.GObject):
    """Used to notify users of available updates"""

    __gsignals__ = {
        'notify-action': (GObject.SignalFlags.RUN_FIRST, None, (str, ))
    }

    def __init__(self, summary, body):
        GObject.GObject.__init__(self)
        Notify.init('Yum Extender')
        icon = "yumex-dnf"
示例#51
0
def images_location():
    return os.path.join(BaseDirectory.save_config_path('rst2wp', 'published'),
                        'images')
示例#52
0
# in relative paths, else the standard paths are used
if os.path.isfile(os.path.join('data', 'glivesnmp.png')):
    DIR_PREFIX = '.'
    DIR_LOCALE = os.path.join(DIR_PREFIX, 'locale')
    DIR_DOCS = os.path.join(DIR_PREFIX, 'doc')
else:
    DIR_PREFIX = os.path.join(sys.prefix, 'share', 'glivesnmp')
    DIR_LOCALE = os.path.join(sys.prefix, 'share', 'locale')
    DIR_DOCS = os.path.join(sys.prefix, 'share', 'doc', 'glivesnmp')
# Set the paths for the folders
DIR_DATA = os.path.join(DIR_PREFIX, 'data')
DIR_UI = os.path.join(DIR_PREFIX, 'ui')
try:
    # In read-only environments, the settings folder cannot be created
    # (eg in a Debian pbuilder fakeroot)
    DIR_SETTINGS = BaseDirectory.save_config_path(DOMAIN_NAME)
    DIR_HOSTS = BaseDirectory.save_config_path(
        os.path.join(DOMAIN_NAME, 'hosts'))
except:
    # Get the settings path without actually creating it
    DIR_SETTINGS = os.path.join(BaseDirectory.xdg_config_home, DOMAIN_NAME)
    DIR_HOSTS = os.path.join(BaseDirectory.xdg_config_home, DOMAIN_NAME,
                             'hosts')
# Set the paths for the data files
FILE_ICON = os.path.join(DIR_DATA, 'glivesnmp.png')
FILE_CONTRIBUTORS = os.path.join(DIR_DOCS, 'contributors')
FILE_TRANSLATORS = os.path.join(DIR_DOCS, 'translators')
FILE_LICENSE = os.path.join(DIR_DOCS, 'license')
FILE_RESOURCES = os.path.join(DIR_DOCS, 'resources')
# Set the paths for configuration files
FILE_SETTINGS = os.path.join(DIR_SETTINGS, 'settings.conf')
示例#53
0
]
OSD_ICON = [
    "notification-audio-volume-high",  # > 66%
    "notification-audio-volume-medium",  # > 33%
    "notification-audio-volume-low",  # > 0%
    "notification-audio-volume-muted",  # = 0%
]
DEBUG = False
CLI = False
GUI = False
CLI_OPTS = {'volume': "+0", 'mute': "none", 'notify': "none"}
CARD_LIST = []
MIXER_LIST = {}
if XDG:
    CONFIG_FILE_PATH = os.path.join(
        BaseDirectory.save_config_path(__appname__),
        "%s.rc" % __appname__,
    )
else:
    CONFIG_FILE_PATH = os.path.join(
        os.environ["HOME"],
        ".%s.rc" % __appname__,
    )

CONFIG_GUI_PATH = "alsa_tray/alsa_tray_config.glade"
MIXER_ICON_PATH = "pixmaps/mixer_icon.png"
AT_ICON_PATH = "pixmaps/alsa-tray_icon.png"


class Timer(object):
    """A basic timer.
示例#54
0
文件: __init__.py 项目: c1sc0/PGPgram
class Db:
    """The data handling object for pgpgram.

    Args:
        verbose (int): level of
    """

    config_path = BaseDirectory.save_config_path(name)
    data_path = BaseDirectory.save_data_path(name)
    cache_path = BaseDirectory.save_cache_path(name)
    executable_path = dirname(realpath(__file__))

    def __init__(self, verbose=0):
        self.verbose = verbose

        # Load files list from disk into 'files' attribute
        try:
            self.files = load(path_join(self.config_path, "files.pkl"))
        except FileNotFoundError as e:
            if verbose > 0:
                pprint("files pickle not found in path, initializing")
            self.files = []

        # Load configuration from disk into 'config' attribute
        try:
            self.config = load(path_join(self.config_path, "config.pkl"))

        except FileNotFoundError as e:
            # Init configuration
            if verbose > 0:
                pprint("Config file not found in path, initializing")

            self.config = {"db key": random_id(20)}

            # Paths
            index_dir = path_join(self.data_path, "index")
            tdlib_dir = path_join(self.data_path, 'tdlib')
            tdlib_config_symlink = path_join(self.config_path, "tdlib")
            tdlib_documents_dir = path_join(self.cache_path, "documents")
            tdlib_documents_symlink = path_join(tdlib_dir, "documents")

            # Init paths
            if not exists(index_dir):
                mkdir(index_dir)

            if not exists(tdlib_dir):
                mkdir(tdlib_dir)
                mkdir(tdlib_documents_dir)
                symlink(tdlib_dir, tdlib_config_symlink)
                symlink(tdlib_documents_dir, tdlib_documents_symlink)

        # Load index
        try:
            self.index = load(path_join(self.data_path, "index.pkl"))
        except:
            if verbose > 0:
                print("index still not built")
        self.save()

    def save(self):
        """Save db

            Formats db in a format compatible with trovotutto,
            builds the trovotutto index and then save the following to disk:
            - search index
            - files list
            - configuration
        """
        pgpgram_db = PGPgramDb(self, filetype="any", exclude=[], update=True)
        self.index = Index(pgpgram_db, slb=3, verbose=self.verbose)
        save(self.index, path_join(self.data_path, "index.pkl"))
        save(self.files, path_join(self.config_path, "files.pkl"))
        save(self.config, path_join(self.config_path, "config.pkl"))

    def search(self,
               query,
               path=getcwd(),
               filetype="any",
               exclude=[],
               results_number=10,
               reverse=True,
               verbose=0):

        if filetype != "any" or path != getcwd():
            word_shortest = min([len(w) for w in query.split(" ")])
            pgpgram_db_kwargs = {
                'path': path,
                'filetype': filetype,
                'exclude': exclude,
                'update': True
            }
            pgpgram_db = PGPgramDb(self, **pgpgram_db_kwargs)
            self.index = Index(pgpgram_db, slb=word_shortest, verbose=verbose)

        results = self.index.search(query)

        self.display_results(results[:results_number], reverse=reverse)

        if results != []:
            choice = int(input("Select file to restore (number): "))
            f = next(d for d in self.files
                     if d['path'] == results[choice])["name"]
            restore = Restore(f, download_directory=getcwd(), verbose=verbose)

    def display_results(self, results, reverse=True):
        lines = []
        for i, f in enumerate(results):
            g = f.split("/")
            result = {
                "title":
                "{}{}. {}{}{}".format(color.GREEN + color.BOLD, i, color.BLUE,
                                      g[-1], color.END),
                "subtitle":
                "{}{}{}\n".format(color.GRAY, f, color.END)
            }
            lines.append(result)

        if reverse: lines.reverse()

        for result in lines:
            print(result['title'])
            print(result['subtitle'])

    def import_file(self, filename):
        files = load(filename)
        for f in files:
            if not f['hash'] in [g['hash'] for g in self.files]:
                self.files.append(f)
                print("adding {}".format(f['name']))
        self.save()
示例#55
0
# -*- coding: utf-8 -*-

import ConfigParser
import logging
import os
import pkg_resources
import shutil
import sys
from xdg import BaseDirectory

config_files_directory = BaseDirectory.save_config_path('fonction-publique')

app_name = os.path.splitext(os.path.basename(__file__))[0]
log = logging.getLogger(app_name)


def check_template_config_files():
    config_ini_path = os.path.join(config_files_directory, 'config.ini')
    config_template_ini_path = os.path.join(config_files_directory,
                                            'config_template.ini')

    if os.path.exists(config_files_directory):
        if not os.path.exists(config_ini_path):
            if not os.path.exists(config_template_ini_path):
                log.info("Creating configuration template files in {}".format(
                    config_files_directory))
                templates_config_files_directory = os.path.join(
                    pkg_resources.get_distribution(
                        'fonction-publique').location)
                shutil.copy(
                    os.path.join(templates_config_files_directory,
示例#56
0
import configparser, os
from xdg import BaseDirectory as base
from xdg import DesktopEntry as desktop
from configparser import ConfigParser

POCO_DESKTOP = 'poco.desktop'
POCO_PACKAGE = 'poco'
DEFAULT_PREFIX_KEY = '<ctrl>q'
DEFAULT_LIST_WORKSPACES = 'true'
DEFAULT_POSITION = 'bottom'
DEFAULT_WIDTH = '800'
DEFAULT_AUTO_HINT = 'true'
DEFAULT_AUTO_SELECT_FIRST_HINT = 'true'

autostart_dir = base.save_config_path("autostart")
autostart_file = os.path.join(autostart_dir, POCO_DESKTOP)
config_dir = base.load_first_config(POCO_PACKAGE)
if not config_dir:
    config_dir = base.save_config_path(POCO_PACKAGE)

config_file_path = os.path.join(config_dir, "poco.cfg")

parser = ConfigParser(interpolation=None)
parser.read(config_file_path)
need_write = False
if not parser.has_section('interface'):
    parser.add_section('interface')
    need_write = True
if not parser.has_option('interface', 'prefix_key'):
    parser.set('interface', 'prefix_key', DEFAULT_PREFIX_KEY)
示例#57
0
pause_game = pygame.image.load("images/pause.png") ##pause image
icon = pygame.image.load("images/snake_pygame-icon.png") ##icon image
pygame.display.set_icon(icon)

## Creation of snake object
snake = pygame.Surface((14, 14))
snake_head = pygame.Surface((14, 14))
snake.fill(DARK_GREEN)
snake_head.fill(GREEN)

## The log files's configuration changes according to the OS in use (Windows, Linux)
OS = platform.system()
if OS == "Linux":
    from xdg import BaseDirectory

    path_data = BaseDirectory.save_config_path("snake-game/") ##set path for log file
    
    ##if the game folder containing the record does not exist, I create it and also create the record.txt file by setting the record to 0 ##
    if not os.path.exists(path_data):
        os.mkdir(path_data) ##if the directory not exists, create dir
elif OS == "Windows": ##the same precedure used for Linux OS
    path_data = os.path.expanduser("~\\") + "snake_pygame\\"
    if not os.path.exists(path_data):
        os.mkdir(path_data)
else: ## for others OS, create directory into game dir
    path_data = ("Record/")
if not os.path.exists(path_data):
    os.mkdir(path_data)


def initialization():