Esempio n. 1
0
def main():
    loglevel = logging.WARN
    if len(sys.argv) == 2 and sys.argv[1] == '-d':
        loglevel = logging.INFO
    logging.basicConfig(level=loglevel,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%F %T')

    save_config_path('udevedu', 'hooks')
    hooks_dir = load_first_config('udevedu', 'hooks')

    hooks = load_hooks(hooks_dir)

    try:
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)

        while True:
            try:
                for args in monitor:
                    # args is (action, device)
                    for h in hooks:
                        spawn_partial(process_hook, h, args)
            except IOError as e:
                if e.errno == errno.EINTR:
                    continue
                logging.warn('Recovering from IOError, continue polling')
                logging.exception(e)
    except KeyboardInterrupt:
        logging.warn('User interrupt, exiting')
Esempio n. 2
0
def get_default_config_dir(filename=None):
    """
    :param filename: if None, only the config path is returned, if provided, a path including the filename will be returned
    :type filename: string
    :returns: a file path to the config directory and optional filename
    :rtype: string

    """
    if windows_check():
        appDataPath = os.environ.get("APPDATA")
        if not appDataPath:
            import _winreg
            hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
            appDataReg = _winreg.QueryValueEx(hkey, "AppData")
            appDataPath = appDataReg[0]
            _winreg.CloseKey(hkey)
        if filename:
            return os.path.join(appDataPath, "deluge", filename)
        else:
            return os.path.join(appDataPath, "deluge")
    else:
        from xdg.BaseDirectory import save_config_path
        try:
            if filename:
                return os.path.join(save_config_path("deluge"), filename)
            else:
                return save_config_path("deluge")
        except OSError, e:
            log.error("Unable to use default config directory, exiting... (%s)", e)
            sys.exit(1)
Esempio n. 3
0
def main():
    loglevel = logging.WARN
    if len(sys.argv) == 2 and sys.argv[1] == '-d':
        loglevel = logging.INFO
    logging.basicConfig(
        level=loglevel,
        format='%(asctime)s %(levelname)s %(message)s',
        datefmt='%F %T'
    )

    save_config_path('udevedu', 'hooks')
    hooks_dir = load_first_config('udevedu', 'hooks')

    hooks = load_hooks(hooks_dir)

    try:
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)

        while True:
            try:
                for args in monitor:
                    # args is (action, device)
                    for h in hooks:
                        spawn_partial(process_hook, h, args)
            except IOError as e:
                if e.errno == errno.EINTR:
                    continue
                logging.warn('Recovering from IOError, continue polling')
                logging.exception(e)
    except KeyboardInterrupt:
        logging.warn('User interrupt, exiting')
Esempio n. 4
0
 def ProfileFilenamePassage(self):
     """ Obtains a valid profile filename
     
     (non-root user) If profile name is not already set (e.g.: default.conf)
     the user is asked for a profile name.
     
     (root user) Profile name and path are already set to "/etc/calise" and 
     "default.conf"
     
     NOTE: pn ~ ProfileName
     
     """
     pn = None
     defaultPath = os.path.join(
         save_config_path(__LowerName__), 'default' + '.conf')
     if not os.path.isfile(defaultPath):
         pn = 'default'
     if pn is None and os.getuid() != 0:
         while True:
             pn = raw_input(customWrap(_(
                 "Please, enter a name for a new profile (use \'default\' "
                 "to overwrite the default profile)") + ": "))
             if pn != pn + os.path.dirname(pn) or pn == "":
                 fprnt(_("Please retry and enter a valid name."))
                 fprnt(_(
                     "Since it\'ll be a filename, chars not supported by "
                     "your os will raise an error") + '\n')
                 time.sleep(1.5)
             elif os.listdir(save_config_path(__LowerName__)).\
                 count(pn + ".conf") > 0:
                 dummy = query_yes_no(customWrap(_(
                     "A profile file with the same name already exists, "
                     "overwrite?")), 'no')
                 if dummy == 'yes':
                     break
             else:
                 break
             sys.stdout.write('\n')
         self.configpath = os.path.join(
             save_config_path(__LowerName__), pn + '.conf')
     elif os.getuid() == 0:
         pn = __LowerName__
         configpath = os.path.join('/', 'etc', pn + '.conf')
         if os.path.isfile(configpath):
             dummy = query_yes_no(customWrap(_(
                 "A global profile already exists, overwrite?")), 'no')
             if dummy == 'no':
                 sys.exit(11)
         self.configpath = configpath
         pn = None
     else:
         self.configpath = os.path.join(
             save_config_path(__LowerName__), pn + '.conf')
     return pn
Esempio n. 5
0
def main():
    loglevel = logging.WARN
    if len(sys.argv) == 2 and sys.argv[1] == "-d":
        loglevel = logging.INFO
    logging.basicConfig(level=loglevel, format="%(asctime)s %(levelname)s %(message)s", datefmt="%F %T")

    save_config_path("udevedu", "hooks")
    hooks_dir = load_first_config("udevedu", "hooks")

    hooks = []

    # Load all hooks
    for fname in sorted(glob.glob(os.path.join(hooks_dir, "*.py"))):
        if not os.path.isfile(fname):
            continue
        logging.info("Loading source %s", fname)

        mod = os.path.splitext(os.path.basename(fname))[0]
        try:
            hooks.append(imp.load_source("udevedu.hooks.%s" % mod, fname))
        except Exception as e:
            logging.error("Loading of %s failed", fname)
            logging.exception(e)

    for h in hooks:
        if hasattr(h, "init"):
            try:
                h.init()
            except Exception as e:
                logging.error("Initialization of %s failed", h.__file__)
                logging.exception(e)

    try:
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)

        while True:
            try:
                for args in monitor:
                    # args is (action, device)
                    for h in hooks:
                        spawn_partial(process_hook, h, args)
            except IOError as e:
                if e.errno == errno.EINTR:
                    continue
                logging.warn("Recovering from IOError, continue polling")
                logging.exception(e)
    except KeyboardInterrupt:
        logging.warn("User interrupt, exiting")
Esempio n. 6
0
    def __init__(self, plugin_dir=None):
        self.config = SafeConfigParser()
        config_path = save_config_path(self.APP_NAME)
        self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
        self.config.read(self.config_file)

        this_dir = os.path.abspath(os.path.dirname(__file__))
        self.plugin_dir = plugin_dir or os.path.join(this_dir,
                                                     self._default_dir)
        places = [
            self.plugin_dir,
        ]
        [
            places.append(os.path.join(path, self.APP_NAME, "evaluators"))
            for path in xdg_data_dirs
        ]

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        self.manager = PluginManagerSingleton.get()
        self.manager.setConfigParser(self.config, self.write_config)
        self.manager.setPluginInfoExtension("expr-plugin")
        self.manager.setPluginPlaces(places)
        self.manager.collectPlugins()
Esempio n. 7
0
def main():
    global rpc
    APP_NAME = 'bch-interlinker'
    NEW_TIP_CHECK_INTERVAL_SECONDS = 5

    config_path = save_config_path(APP_NAME)
    cache_path = save_cache_path(APP_NAME)
    db_path = path.join(cache_path, 'db')
    config_file_path = path.join(config_path, 'config.ini')

    config = configparser.ConfigParser()
    config.read(config_file_path)

    rpc = AuthServiceProxy("http://%s:%s@%s:%s" %
            (config['daemon']['user'], config['daemon']['password'],
                config['daemon']['host'], config['daemon']['port']))

    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d/%m/%y %H:%M:%S %Z')
    logger = logging.getLogger(APP_NAME)
    logger.setLevel(logging.DEBUG)

    tip_id = ''
    while True:
        possibly_new_tip_id = rpc.getbestblockhash()
        if possibly_new_tip_id == tip_id:
            sleep(NEW_TIP_CHECK_INTERVAL_SECONDS)
            continue
        tip_id = possibly_new_tip_id
        logger.info('new block "%s"', tip_id)
        with shelve.open(db_path) as db:
            new_interlink = interlink(tip_id, db)
        logger.debug('new interlink "%s"', new_interlink)
        logger.info('mtr hash "%s"', new_interlink.hash().hex())
        logger.info('velvet tx "%s"', send_velvet_tx(new_interlink.hash()))
Esempio n. 8
0
def main():
    config = configparser.ConfigParser()

    config_path = save_config_path("qrdisplay")
    config_filename = path.join(config_path, "config")

    if not path.isfile(config_filename):
        print("Creating the config file")
        ssid = raw_input("SSID: ")
        key = getpass.getpass("Key: ")
        config['WIFI'] = {
            'ssid': ssid,
            'key': key
        }
        with open(config_filename, 'w') as config_file:
            config.write(config_file)
        sys.exit(0)
    else:
        config.read(config_filename)
        ssid = config['WIFI']['ssid']
        key = config['WIFI']['key']
        GPIO.setmode(GPIO.BCM)
        wifi.display_qr_code(ssid, key)
        wifi_button = Button(5)
        wifi_button.when_pressed = wifi.create_event_callback(ssid, key)
        midnight = True
        while True:
            if midnight:
                wifi.display_qr_code(ssid, key)
                # Wait an additional hour to prevent a fast refresh
                time.sleep(3600)
            time.sleep(3600)
            midnight = datetime.now().hour == 0
Esempio n. 9
0
def get_default_config_dir(filename=None):
    """
    :param filename: if None, only the config directory path is returned,
                     if provided, a path including the filename will be returned
    :type  filename: string
    :returns: a file path to the config directory and optional filename
    :rtype: string

    """

    if os.access(DEFAULT_CONFIG_PATH, os.F_OK):
        return DEFAULT_CONFIG_PATH

    user_config_path = os.path.join(os.path.expanduser("~/.config"),
                                   "mirror")

    if not os.access(user_config_path, os.F_OK):
        return DEFAULT_CONFIG_PATH

    try:
        from xdg.BaseDirectory import save_config_path
        config_path = save_config_path("mirror")
    except:
        config_path = user_config_path

    if not filename:
        filename = ''

    return os.path.join(config_path, filename)
Esempio n. 10
0
def get_default_config_dir(filename=None):
    """
    :param filename: if None, only the config path is returned, if provided,
                     a path including the filename will be returned
    :type filename: string
    :returns: a file path to the config directory and optional filename
    :rtype: string

    """

    if windows_check():
        def save_config_path(resource):
            app_data_path = os.environ.get('APPDATA')
            if not app_data_path:
                try:
                    import winreg
                except ImportError:
                    import _winreg as winreg  # For Python 2.
                hkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
                app_data_reg = winreg.QueryValueEx(hkey, 'AppData')
                app_data_path = app_data_reg[0]
                winreg.CloseKey(hkey)
            return os.path.join(app_data_path, resource)
    else:
        from xdg.BaseDirectory import save_config_path
    if not filename:
        filename = ''
    try:
        return decode_bytes(os.path.join(save_config_path('deluge'), filename))
    except OSError as ex:
        log.error('Unable to use default config directory, exiting... (%s)', ex)
        sys.exit(1)
Esempio n. 11
0
def do_first_run():
    if platform.system() in ('Windows', 'Microsoft'):
        auth_path = os.path.join(os.environ['APPDATA'], 'deluge')
    else:
        try:
            from xdg.BaseDirectory import save_config_path
        except ImportError:
            return
        
        auth_path = save_config_path('deluge')
    
    auth_path = os.path.join(auth_path, 'auth')
    if not os.path.isfile(auth_path):
        return
    
    with open(auth_path, 'rb') as f:
        filedata = f.read().split('\n')[0].split(':')
        if len(filedata) < 2:
            return
        
        username, password = filedata[:2]
    
    plugin.set_setting('ip', '127.0.0.1')
    plugin.set_setting('port', '58846')
    plugin.set_setting('username', username)
    plugin.set_setting('password', password)
Esempio n. 12
0
    def __init__(self):
        """
        Initialize the PluginManager including:
            - plugin configuration directory
            - plugin search locations
        """
        self.config_path = save_config_path("yasibo")
        self.config_file = os.path.join(self.config_path, "plugins.conf")
        places = []
        [places.append(os.path.join(path, "yasibo", "plugins")) for path in xdg_data_dirs]
        # dev location
        places.append("%s/../plugins" % os.path.dirname(os.path.abspath(__file__)))

        PluginManagerSingleton.setBehaviour([ConfigurablePluginManager,
                                             VersionedPluginManager])
        self.manager = PluginManagerSingleton.get()
        locator = self.manager.getPluginLocator()
        locator.setPluginInfoExtension("yasibo-plugin")
        self.manager.setPluginPlaces(places)

        self.config = SafeConfigParser()
        self.config.read(self.config_file)
        self.manager.setConfigParser(self.config, self.save)

        self.manager.collectPlugins()
        log.debug("Config file: %s" % self.config_file)
Esempio n. 13
0
 def _read_config(self):
     config_path = os.path.join(save_config_path('tunedmode'),
                                'tunedmode.ini')
     self.config.read_dict(CONFIG_DEFAULTS)
     self.config.read(config_path)
     if not os.path.isfile(config_path):
         with open(config_path, 'w') as config_file:
             self.config.write(config_file)
Esempio n. 14
0
 def __init__(self, filename):
     '''Initialize config object'''
     assert (filename is not None)
     OrderedDict.__init__(self)
     path = save_config_path(XDG_DIRECTORY)
     self.path = join(path, filename)
     if not isinstance(self.path, str) or not exists(self.path):
         raise MissingConfigFile(self.path)
     self.load()
Esempio n. 15
0
def checkCalibrationNeed(suffix='.conf', default='default'):
    defName = default
    defConf = '%s%s' % (
        os.path.join(save_config_path(__LowerName__), defName), suffix)
    sysConf = '%s%s' % (
        os.path.join(os.path.join('/', 'etc', __LowerName__)), suffix)
    if not os.path.isfile(defConf) and not os.path.isfile(sysConf):
        options.settings['configure'] = True
    return options.settings['configure']
Esempio n. 16
0
 def __init__(self, filename):
     '''Initialize config object'''
     assert(filename is not None)
     OrderedDict.__init__(self)
     path = save_config_path(XDG_DIRECTORY)
     self.path = join(path, filename)
     if not isinstance(self.path, str) or not exists(self.path):
         raise MissingConfigFile(self.path)
     self.load()
Esempio n. 17
0
def checkCalibrationNeed(suffix='.conf', default='default'):
    defName = default
    defConf = '%s%s' % (os.path.join(save_config_path(__LowerName__),
                                     defName), suffix)
    sysConf = '%s%s' % (os.path.join(os.path.join('/', 'etc',
                                                  __LowerName__)), suffix)
    if not os.path.isfile(defConf) and not os.path.isfile(sysConf):
        options.settings['configure'] = True
    return options.settings['configure']
Esempio n. 18
0
    def __init__(self, app):
        GObject.__init__(self)

        self.app = app
        self._config = ConfigParser()
        self._filename = os.path.join(save_config_path("garmon"), "config")
        self._config.read(self._filename)
        
        self._dialog = _PrefsDialog()
        
        self._watches = []
Esempio n. 19
0
    def __init__(self, app):
        GObject.__init__(self)

        self.app = app
        
        self._config = ConfigParser()
        self._filename = os.path.join(save_config_path("garmon"), "config")
        self._config.read(self._filename)
        
        self._dialog = _PrefsDialog()
        
        self._watches = []
Esempio n. 20
0
    def __init__(self):
        from xdg.BaseDirectory import save_config_path, save_data_path
        # TODO: Should we use save_config_path or load_first_config?
        self.config_dir = save_config_path('coinbox')

        self.data_dir = save_data_path('coinbox')

        # TODO: the default locale directory should be determined in a better way
        #         some package it in the egg as resources (yuck)
        #         some have a $prefix set up, and from that determine the path to $prefix/share/locale
        #         some have it in the data directory
        self.locale_dir = '/usr/share/locale'
Esempio n. 21
0
 def __init__(self):
     from xdg.BaseDirectory import save_config_path, save_data_path
     # TODO: Should we use save_config_path or load_first_config?
     self.config_dir = save_config_path('coinbox')
     
     self.data_dir = save_data_path('coinbox')
     
     # TODO: the default locale directory should be determined in a better way
     #         some package it in the egg as resources (yuck)
     #         some have a $prefix set up, and from that determine the path to $prefix/share/locale
     #         some have it in the data directory
     self.locale_dir = '/usr/share/locale'
Esempio n. 22
0
    def __init__(self, version, pkgdatadir, icondir):
        self.version = version
        self.datadir = pkgdatadir
        self.icondir = icondir
        self.udev_path = self.datadir + '/udev/'
        self.target_dir = '/etc/udev/rules.d/'
        self.profile_path = os.path.join(save_config_path('oversteer'),
                                         'profiles')
        self.device_manager = None

        if not os.path.isdir(self.udev_path):
            self.udev_path = None
Esempio n. 23
0
    def _get_local_auth(self):
        auth_file = ""
        username = password = ""
        if platform.system() in ('Windows', 'Microsoft'):
            appDataPath = os.environ.get("APPDATA")
            if not appDataPath:
                try:
                    import winreg
                except ImportError:
                    import _winreg as winreg

                hkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"
                )
                appDataReg = winreg.QueryValueEx(hkey, "AppData")
                appDataPath = appDataReg[0]
                winreg.CloseKey(hkey)

            auth_file = os.path.join(appDataPath, "deluge", "auth")
        else:
            from xdg.BaseDirectory import save_config_path
            try:
                auth_file = os.path.join(save_config_path("deluge"), "auth")
            except OSError:
                return username, password

        if os.path.exists(auth_file):
            for line in open(auth_file):
                if line.startswith("#"):
                    # This is a comment line
                    continue
                line = line.strip()
                try:
                    lsplit = line.split(":")
                except Exception:
                    continue

                if len(lsplit) == 2:
                    username, password = lsplit
                elif len(lsplit) == 3:
                    username, password, level = lsplit
                else:
                    continue

                if username == "localclient":
                    return (username, password)

        return ("", "")
Esempio n. 24
0
 def _init_config(self):
     """
     Initialize configuration parser and the filename that the parser will
     write to.        
     """
     # TODO: use GSettings instead
     self._config = SafeConfigParser()
     # read config from the first found config file
     filename = self.package + ".conf"
     config_file = self._find_config_file(filename)
     if config_file:
         self.debug("Loading configuration from %s", config_file)
         self._config.read(config_file)
     # always write config to save_config_path
     self._config_file = os.path.join(save_config_path(self._package), filename)
Esempio n. 25
0
def main():
    """Read the config, creating it if necessary, then loop on (re)starting the bot"""
    config_path = os.path.join(save_config_path("notifybot"), "rc.conf")
    if not os.path.exists(config_path):
        new_config(config_path)
    with open(config_path) as f:
        config = json.load(f)
    while True:
        try:
            start_bot(config["user"], config["password"])
        except KeyboardInterrupt:
            break
        except Exception as e:
            print "Got Exception %s, retrying in 10s" % e
            time.sleep(10)
Esempio n. 26
0
def clear_config():
    """Remove configuration section from files on disk."""
    config_dir = save_config_path('snapcraft')
    filename = os.path.join(config_dir, 'snapcraft.cfg')

    parser = ConfigParser()
    if os.path.exists(filename):
        parser.read(filename)

    api_endpoint = os.environ.get(
        'UBUNTU_SSO_API_ROOT_URL', UBUNTU_SSO_API_ROOT_URL)
    location = urlparse(api_endpoint).netloc
    parser.remove_section(location)

    with open(filename, 'w') as fd:
        parser.write(fd)
Esempio n. 27
0
    def __init__(self, plugin_dir=None):
        self.config = SafeConfigParser()
        config_path = save_config_path(self.APP_NAME)
        self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
        self.config.read(self.config_file)

        this_dir = os.path.abspath(os.path.dirname(__file__))
        self.plugin_dir = plugin_dir or os.path.join(this_dir, self._default_dir)
        places = [self.plugin_dir]
        [places.append(os.path.join(path, self.APP_NAME, "evaluators")) for path in xdg_data_dirs]

        PluginManagerSingleton.setBehaviour([ConfigurablePluginManager, VersionedPluginManager])

        self.manager = PluginManagerSingleton.get()
        self.manager.setConfigParser(self.config, self.write_config)
        self.manager.setPluginInfoExtension("expr-plugin")
        self.manager.setPluginPlaces(places)
        self.manager.collectPlugins()
Esempio n. 28
0
def get_default_config_dir(filename=None):
    """
    :param filename: if None, only the config directory path is returned,
                     if provided, a path including the filename will be returned
    :type  filename: string
    :returns: a file path to the config directory and optional filename
    :rtype: string

    """

    from xdg.BaseDirectory import save_config_path
    if not filename:
        filename = ''
    try:
        return os.path.join(save_config_path("mirror"), filename)
    except OSError, e:
        log.error("Unable to use default config directory, exiting... (%s)", e)
        sys.exit(1)
Esempio n. 29
0
    def _get_local_auth(self):
        username = password = ""
        if platform.system() in ('Windows', 'Microsoft'):
            app_data_path = os.environ.get("APPDATA")
            if not app_data_path:
                from six.moves import winreg
                hkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                )
                app_data_reg = winreg.QueryValueEx(hkey, "AppData")
                app_data_path = app_data_reg[0]
                winreg.CloseKey(hkey)

            auth_file = os.path.join(app_data_path, "deluge", "auth")
        else:
            from xdg.BaseDirectory import save_config_path
            try:
                auth_file = os.path.join(save_config_path("deluge"), "auth")
            except OSError:
                return username, password

        if os.path.exists(auth_file):
            for line in open(auth_file):
                if line.startswith("#"):
                    # This is a comment line
                    continue
                line = line.strip()
                try:
                    lsplit = line.split(":")
                except Exception:
                    continue

                if len(lsplit) == 2:
                    username, password = lsplit
                elif len(lsplit) == 3:
                    username, password, level = lsplit
                else:
                    continue

                if username == "localclient":
                    return username, password

        return "", ""
Esempio n. 30
0
    def _get_local_auth(self):
        username = password = ''
        if platform.system() in ('Windows', 'Microsoft'):
            app_data_path = os.environ.get('APPDATA')
            if not app_data_path:
                from six.moves import winreg
                hkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
                )
                app_data_reg = winreg.QueryValueEx(hkey, 'AppData')
                app_data_path = app_data_reg[0]
                winreg.CloseKey(hkey)

            auth_file = os.path.join(app_data_path, 'deluge', 'auth')
        else:
            from xdg.BaseDirectory import save_config_path
            try:
                auth_file = os.path.join(save_config_path('deluge'), 'auth')
            except OSError:
                return username, password

        if os.path.exists(auth_file):
            for line in open(auth_file):
                if line.startswith('#'):
                    # This is a comment line
                    continue
                line = line.strip()
                try:
                    lsplit = line.split(':')
                except Exception:
                    continue

                if len(lsplit) == 2:
                    username, password = lsplit
                elif len(lsplit) == 3:
                    username, password, level = lsplit
                else:
                    continue

                if username == 'localclient':
                    return username, password

        return '', ''
Esempio n. 31
0
    def _get_local_auth(self):
        auth_file = ""
        username = password = ""
        if platform.system() in ('Windows', 'Microsoft'):
            appDataPath = os.environ.get("APPDATA")
            if not appDataPath:
                import _winreg
                hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
                appDataReg = _winreg.QueryValueEx(hkey, "AppData")
                appDataPath = appDataReg[0]
                _winreg.CloseKey(hkey)

            auth_file = os.path.join(appDataPath, "deluge", "auth")
        else:
            from xdg.BaseDirectory import save_config_path
            try:
                auth_file = os.path.join(save_config_path("deluge"), "auth")
            except OSError, e:
                return username, password
Esempio n. 32
0
def get_default_config_dir(filename=None):
    """
    :param filename: if None, only the config directory path is returned,
                     if provided, a path including the filename will be returned
    :type  filename: string
    :returns: a file path to the config directory and optional filename
    :rtype: string

    """

    try:
        from xdg.BaseDirectory import save_config_path
        config_path = save_config_path("mirror")
    except:
        config_path = os.path.join(os.path.expanduser("~/.config"),
                                   "mirror")
    if not filename:
        filename = ''
    return os.path.join(config_path, filename)
Esempio n. 33
0
def save_config(data):
    """Store current configuration to disk."""
    config_dir = save_config_path('snapcraft')
    filename = os.path.join(config_dir, 'snapcraft.cfg')

    parser = ConfigParser()
    if os.path.exists(filename):
        parser.read(filename)

    api_endpoint = os.environ.get(
        'UBUNTU_SSO_API_ROOT_URL', UBUNTU_SSO_API_ROOT_URL)
    location = urlparse(api_endpoint).netloc
    if not parser.has_section(location):
        parser.add_section(location)

    for key, value in data.items():
        parser.set(location, key, str(value))

    with open(filename, 'w') as fd:
        parser.write(fd)
def get_localhost_auth():
    try:
        from xdg.BaseDirectory import save_config_path
    except ImportError:
        return (None, None)
    path = os.path.join(save_config_path("deluge"), "auth")
    if not os.path.exists(path):
        return (None, None)
    with open(path) as f:
        for line in f:
            if line.startswith("#"):
                continue
            line = line.strip()
            lsplit = line.split(":")

            if len(lsplit) in (2, 3):
                username, password = lsplit[:2]

            if username == "localclient":
                return (username, password)
    return (None, None)
Esempio n. 35
0
def events_path() -> str:
    """Path where user event definitions are loaded from.

    They can be .py or .txt files.
    """
    return save_config_path('agenda')
Esempio n. 36
0
import json
import os
import sys

from xdg.BaseDirectory import save_config_path

from tordl import engines

CFG_DIR = os.path.join(
    os.path.expanduser('~'), save_config_path('torrentdl')
)
CFG_FILE = os.path.join(CFG_DIR, 'config.json')
CFG_ENGINES_FILE = os.path.join(CFG_DIR, 'engines.py')
CFG_HISTORY_FILE = os.path.join(CFG_DIR, 'search_history.txt')

SEARCH_ENGINES = ['Zooqle', 'TPB', 'Lime', '1337x', 'Glo', 'KAT', 'Solid']
TORRENT_CLIENT_CMD = 'qbittorrent %s'
BROWSER_CMD = 'firefox %s'
HISTORY_MAX_LENGTH = 100
PAGE_NUM_DOWNLOAD = 1
REQUEST_TIMEOUT = 5
AGGREGATE_SAME_MAGNET_LINKS = True
FETCH_MISSING_MAGNET_LINKS = False
FETCH_MAGNET_LINKS_CONCURRENCE = 20


def mk_cfg():
    mod = sys.modules[__name__]
    attrs = dir(mod)
    omit = (
        'os',
Esempio n. 37
0
File: config.py Progetto: gsy/gmusic
 def write(self):
     """写入config文件,路径由xdg决定"""        
     filename = os.path.join(save_config_path("gmusic"), "config")
     with open(filename, "w") as configfile:
         self.config.write(configfile)
Esempio n. 38
0
def make_new_config(config_path):
    import getpass
    user = raw_input("Please enter the Jabber ID for your bot: ")
    while True:
        attempt1 = getpass.getpass("Please enter the Jabber password: "******"Please confirm the Jabber password: "******"Please enter your download directory: ")
    with open(config_path, "wb") as f:
        json.dump({
            "user": user,
            "password": password,
            "max_parallel_downloads": 3,
            "download_directory": dl_dir
            }, indent = 4, fp = f)
    print("config saved in %s" % config_path)

if __name__ == "__main__":
    config_path = os.path.join(save_config_path("plowbot"), "plowbotrc")
    if not os.path.exists(config_path):
        make_new_config(config_path)
    with open(config_path) as f:
        config = json.load(f)
        bot = PlowBot(**config)
        t = threading.Thread(target = bot.download_loop)
        t.daemon = True
        bot.serve_forever(connect_callback = lambda: t.start())
    def __init__(self):
        self._create_window()
        
        # Setup a ConfigParser which will be used by the Yapsy plugin manager to
        # remember which plugins are activated. The  function
        # xdg.BaseDirectory.save_config_path() function is used to get the path 
        # for the configuration file. You may want to instead iterate over the
        # xdg.BaseDirectory.xdg_config_dirs if your application installs default
        # configuration files into system directories. See
        # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
        # for more information on the XDG specifications.
        
        self.config = SafeConfigParser()
        config_path = save_config_path(self.APP_NAME)
        self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
        logging.debug("Reading configuration file: %s" % self.config_file)
        self.config.read(self.config_file)
        
        # Build a list of directories which may contain plugins. This will 
        # include the 'plugins' folder where this file resides as well as every
        # directory in xdg.BaseDirectory.xdg_data_dirs. This way users can
        # install plugins in something like ~/.local/yapsy-gtk-example/plugins
        # but your installer could also install those plugins to something like
        # /usr/share/yapsy-gtk-example/plugins. You'll see Yapsy checking each
        # of these directories if logging is set to logging.DEBUG
        
        this_dir = os.path.abspath(os.path.dirname(__file__))
        plugin_dir = os.path.join(this_dir,'plugins')
        places = [plugin_dir,]
        [places.append(os.path.join(path, self.APP_NAME, "plugins")) for path 
            in xdg_data_dirs]
        
        # The singleton versino of the Yapsy plugin manager is used rather than
        # passing around a PluginManager instance. Prior to getting the 
        # singleton instance, some "plugin manager decorators" are installed to:
        # 1. Automatically save active and non-active plugins to the config file
        # 2. Ensure only the newest versions of plugins are used.
        # This call to setBehaviour() must occur before getting the singleton 
        # instance.
        
        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])
        
        # Get singleton instance
        manager = PluginManagerSingleton.get()
        
        # I like to give the manager a reference to the application class so
        # that plugins can connect to signals and access windows through
        # the manager singleton. 
        manager.app = self
        
        # Give manager the config file and a callback function to call when it
        # changes the config (eg. when a plugin is activated or deactivated).
        manager.setConfigParser(self.config, self.write_config)
        
        # Setup a file extension for plugin information files. In this it's 
        # just ".plugin" but you may want to do something specific to your
        # application like ".myapp-plugin"
        manager.setPluginInfoExtension("plugin")
        
        # Pass the manager the list of plugin directories
        manager.setPluginPlaces(places)

        # CollectPlugins is a shortcut for locatePlugins() and loadPlugins().
        manager.collectPlugins()
        
        # Now that the plugins have been collected, the plugin widget can
        # be refreshed to display all installed plugins.
        self._plugin_list.refresh()
Esempio n. 40
0
    def __init__(self, application, model, argv):
        self.app = application
        self.locale = ''
        self.check_permissions = True
        self.device_manager = self.app.device_manager
        self.device = None
        self.grab_input = False
        self.test = None
        self.linear_chart = None
        self.performance_chart = None
        self.combined_chart = None
        self.button_setup_step = False
        self.button_config = [-1] * 9
        self.button_config[0] = [-1]
        self.pressed_button_count = 0

        signal.signal(signal.SIGINT, self.sig_int_handler)

        self.config_path = save_config_path('oversteer')

        self.load_preferences()

        self.profile_path = os.path.join(self.config_path, 'profiles')
        if not os.path.isdir(self.profile_path):
            os.makedirs(self.profile_path, 0o700)

        self.ui = GtkUi(self, argv)
        self.ui.set_app_version(self.app.version)
        self.ui.set_app_icon(
            os.path.join(self.app.icondir, 'org.berarma.Oversteer.svg'))
        self.ui.set_languages(self.languages)

        self.ui.set_language(self.locale)
        self.ui.set_check_permissions(self.check_permissions)

        self.populate_window()

        if self.app.args.profile is not None:
            self.ui.set_profile(self.app.args.profile)

        self.model = None
        if model.device is not None:
            model.set_ui(self.ui)
            self.models = {
                model.device.get_id(): model,
            }
        else:
            self.models = {}

        if model.device is not None:
            self.ui.set_device_id(model.device.get_id())
            self.change_device(model.device.get_id())

        self.ui.update()

        Thread(target=self.input_thread, daemon=True).start()

        self.ui.start()

        if self.app.args.command:
            if not model.get_start_app_manually():
                self.start_app()
            else:
                self.ui.enable_start_app()

        self.ui.main()
    def __init__(self):
        self._create_window()

        # Setup a ConfigParser which will be used by the Yapsy plugin manager to
        # remember which plugins are activated. The  function
        # xdg.BaseDirectory.save_config_path() function is used to get the path
        # for the configuration file. You may want to instead iterate over the
        # xdg.BaseDirectory.xdg_config_dirs if your application installs default
        # configuration files into system directories. See
        # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
        # for more information on the XDG specifications.

        self.config = SafeConfigParser()
        config_path = save_config_path(self.APP_NAME)
        self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
        logging.debug("Reading configuration file: %s" % self.config_file)
        self.config.read(self.config_file)

        # Build a list of directories which may contain plugins. This will
        # include the 'plugins' folder where this file resides as well as every
        # directory in xdg.BaseDirectory.xdg_data_dirs. This way users can
        # install plugins in something like ~/.local/yapsy-gtk-example/plugins
        # but your installer could also install those plugins to something like
        # /usr/share/yapsy-gtk-example/plugins. You'll see Yapsy checking each
        # of these directories if logging is set to logging.DEBUG

        this_dir = os.path.abspath(os.path.dirname(__file__))
        plugin_dir = os.path.join(this_dir, 'plugins')
        places = [
            plugin_dir,
        ]
        [
            places.append(os.path.join(path, self.APP_NAME, "plugins"))
            for path in xdg_data_dirs
        ]

        # The singleton versino of the Yapsy plugin manager is used rather than
        # passing around a PluginManager instance. Prior to getting the
        # singleton instance, some "plugin manager decorators" are installed to:
        # 1. Automatically save active and non-active plugins to the config file
        # 2. Ensure only the newest versions of plugins are used.
        # This call to setBehaviour() must occur before getting the singleton
        # instance.

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        # Get singleton instance
        manager = PluginManagerSingleton.get()

        # I like to give the manager a reference to the application class so
        # that plugins can connect to signals and access windows through
        # the manager singleton.
        manager.app = self

        # Give manager the config file and a callback function to call when it
        # changes the config (eg. when a plugin is activated or deactivated).
        manager.setConfigParser(self.config, self.write_config)

        # Setup a file extension for plugin information files. In this it's
        # just ".plugin" but you may want to do something specific to your
        # application like ".myapp-plugin"
        manager.setPluginInfoExtension("plugin")

        # Pass the manager the list of plugin directories
        manager.setPluginPlaces(places)

        # CollectPlugins is a shortcut for locatePlugins() and loadPlugins().
        manager.collectPlugins()

        # Now that the plugins have been collected, the plugin widget can
        # be refreshed to display all installed plugins.
        self._plugin_list.refresh()
Esempio n. 42
0
import json
import os
import sys

from xdg.BaseDirectory import save_config_path

from tordl import engines

CFG_DIR = os.path.join(os.path.expanduser('~'), save_config_path('torrentdl'))
CFG_FILE = os.path.join(CFG_DIR, 'config.json')
CFG_ENGINES_FILE = os.path.join(CFG_DIR, 'engines.py')
CFG_HISTORY_FILE = os.path.join(CFG_DIR, 'search_history.txt')

SEARCH_ENGINES = [
    '1337x', 'BTDB', 'Glo', 'KAT', 'Lime', 'Nyaa', 'Solid', 'TGx', 'TPB',
    'Zooqle'
]
TORRENT_CLIENT_CMD = 'qbittorrent %s'
BROWSER_CMD = 'firefox %s'

HISTORY_MAX_LENGTH = 100

PAGE_NUM_DOWNLOAD = 1
REQUEST_TIMEOUT = 5

AGGREGATE_SAME_MAGNET_LINKS = True
FETCH_MISSING_MAGNET_LINKS = False
FETCH_MAGNET_LINKS_CONCURRENCE = 20

USE_EXCLUDE_SEARCH = True
EXCLUDE_SEARCH_DELIMITER = '::-'
Esempio n. 43
0
import logging
import os
import configparser
from xdg.BaseDirectory import save_config_path, load_config_paths

logger = logging.getLogger(__name__)

config_dir = save_config_path('python-magnatune')

AUTHORIZED_OPTIONS = {'verbose': False,
                      'quiet': False,
                      'format': 'ogg',
                      'dlformat': 'web',
                      'login': None,
                      'extract': None}


def setdefault_from_config(args):
    config = {}
    for f in load_config_paths('python-magnatune', 'config.ini'):
        logger.debug('Reading form config file: %s', f)
        parser = configparser.ConfigParser()
        try:
            parser.read(f)
            for option, value in parser['magnatune'].items():
                if option not in AUTHORIZED_OPTIONS:
                    logger.warning('Option "%s" in config file %s will be ignored', option, f)
                else:
                    config.setdefault(option, value)
        except configparser.Error as e:
            logger.warning("Error while reading the config file %s, ignoring :\n%s", f, e)
Esempio n. 44
0
 def _credentials_file(self):
     """Path to per-user file with SSO credentials"""
     return os.path.join(
         save_config_path('ubuntu-image'), 'credentials.ini')
Esempio n. 45
0
from os import path
import math
import configparser
from itertools import chain, zip_longest, filterfalse
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from xdg.BaseDirectory import save_cache_path, save_config_path

APP_NAME = 'bch-interlinker'
config_path = save_config_path(APP_NAME)
config_file_path = path.join(config_path, 'config.ini')
config = configparser.ConfigParser()
config.read(config_file_path)

chunk = lambda n, iterable: (filterfalse(lambda x: x == (), chunk) for chunk in (zip_longest(*[iter(iterable)]*n, fillvalue=())))

rpc = AuthServiceProxy("http://%s:%s@%s:%s" %
            (config['daemon']['user'], config['daemon']['password'],
                config['daemon']['host'], config['daemon']['port']))

def nice_batch(reqs):
    chunks = chunk(100000, reqs)
    return chain.from_iterable(rpc.batch_(r) for r in chunks)

def command_for_height_range(cmd, range_):
    return nice_batch([cmd, h] for h in range_)

def block_hashes_with_height(range_):
    return command_for_height_range('getblockhash', range_)

def blocks_with_height(range_):
    return nice_batch(['getblock', h] for h in block_hashes_with_height(range_))
Esempio n. 46
0
    def run(self, argv):
        parser = argparse.ArgumentParser(
            prog=argv[0], description=_("Oversteer - Steering Wheel Manager"))
        parser.add_argument('command',
                            nargs='*',
                            help=_("Run as command's companion"))
        parser.add_argument('--device', help=_("Device path"))
        parser.add_argument('--list',
                            action='store_true',
                            help=_("list connected devices"))
        parser.add_argument('--mode', help=_("set the compatibility mode"))
        parser.add_argument('--range',
                            type=int,
                            help=_("set the rotation range [40-900]"))
        parser.add_argument('--combine-pedals',
                            type=int,
                            dest='combine_pedals',
                            help=_("combine pedals [0-2]"))
        parser.add_argument('--autocenter',
                            type=int,
                            help=_("set the autocenter strength [0-100]"))
        parser.add_argument('--ff-gain',
                            type=int,
                            help=_("set the FF gain [0-100]"))
        parser.add_argument('--spring-level',
                            type=int,
                            help=_("set the spring level [0-100]"))
        parser.add_argument('--damper-level',
                            type=int,
                            help=_("set the damper level [0-100]"))
        parser.add_argument('--friction-level',
                            type=int,
                            help=_("set the friction level [0-100]"))
        parser.add_argument('--ffb-leds',
                            action='store_true',
                            default=None,
                            help=_("enable FFBmeter leds"))
        parser.add_argument('--no-ffb-leds',
                            dest='ffb_leds',
                            action='store_false',
                            default=None,
                            help=_("disable FFBmeter leds"))
        parser.add_argument('--center-wheel',
                            action='store_true',
                            default=None,
                            help=_("center wheel"))
        parser.add_argument('--no-center-wheel',
                            dest='center_wheel',
                            action='store_false',
                            default=None,
                            help=_("don't center wheel"))
        parser.add_argument('--start-manually',
                            action='store_true',
                            default=None,
                            help=_("run command manually"))
        parser.add_argument('--no-start-manually',
                            dest='start_manually',
                            action='store_false',
                            default=None,
                            help=_("don't run command manually"))
        parser.add_argument('-p',
                            '--profile',
                            help=_("load settings from a profile"))
        parser.add_argument('-g',
                            '--gui',
                            action='store_true',
                            help=_("start the GUI"))
        parser.add_argument('--debug',
                            action='store_true',
                            help=_("enable debug output"))
        parser.add_argument('--version',
                            action='store_true',
                            help=_("show version"))

        args = parser.parse_args(argv[1:])
        argc = len(sys.argv[1:])

        if args.version:
            print("Oversteer v" + self.version)
            sys.exit(0)

        if args.debug:
            argc -= 1
        else:
            logging.disable(level=logging.INFO)

        device_manager = DeviceManager()
        device_manager.start()

        if args.list:
            argc -= 1
            devices = device_manager.get_devices()
            print(_("Devices found:"))
            for device in devices:
                print("  {}: {}".format(device.dev_name, device.name))
            sys, exit(0)

        if args.device is not None:
            argc -= 1
            if os.path.exists(args.device):
                device = device_manager.get_device(
                    os.path.realpath(args.device))
                if not device.check_permissions():
                    print(
                        _(("You don't have the required permissions to change your "
                           +
                           "wheel settings. You can fix it yourself by copying the {} "
                           + "file to the {} directory and rebooting.").format(
                               self.udev_file, self.target_dir)))
        else:
            device = device_manager.first_device()

        model = Model(device)

        if args.profile is not None:
            profile_file = os.path.join(save_config_path('oversteer'),
                                        'profiles', args.profile + '.ini')
            if not os.path.exists(profile_file):
                print(_("This profile doesn't exist."))
                sys.exit(2)
            model.load(profile_file)

        if args.start_manually is not None:
            model.set_start_app_manually(args.start_manually)

        start_gui = args.gui or argc == 0 or (model.get_start_app_manually()
                                              and args.command)

        if device is None and not start_gui:
            print(_("No device available."))
            sys.exit(1)

        if args.mode is not None:
            model.set_mode(args.mode)
        if args.range is not None:
            model.set_range(args.range)
        if args.combine_pedals is not None:
            model.set_combine_pedals(args.combine_pedals)
        if args.autocenter is not None:
            model.set_autocenter(args.autocenter)
        if args.ff_gain is not None:
            model.set_ff_gain(args.ff_gain)
        if args.spring_level is not None:
            model.set_spring_level(args.spring_level)
        if args.damper_level is not None:
            model.set_damper_level(args.damper_level)
        if args.friction_level is not None:
            model.set_friction_level(args.friction_level)
        if args.ffb_leds is not None:
            model.set_ffb_leds(1 if args.ffb_leds else 0)
        if args.center_wheel is not None:
            model.set_center_wheel(1 if args.center_wheel else 0)
        if args.start_manually is not None:
            model.set_start_app_manually(1 if args.start_manually else 0)
        if start_gui:
            self.args = args
            self.device_manager = device_manager
            Gui(self, model, argv)
Esempio n. 47
0
File: config.py Progetto: gsy/gmusic
 def load(self):
     """读入config"""
     self.config.read(os.path.join(save_config_path("gmusic"), "config"))