Example #1
0
def main():
    options, args = parser.parse_args()
    
    if len(args) == 1 and args[0].endswith('.odt'):
        args.append(args[0][:-4])
    if len(args) == 2:
        filename, targetdir = args
        convert_odt(filename, targetdir, debug=options.debug,
            options={
                'download_source_link': options.download_source_link
                })
    elif len(args) == 1:
        configname = os.path.abspath(args[0])
        configdir = os.path.dirname(configname)
        config = ConfigParser()
        config.read(configname)
        for section in config.sections():
            filename = config.has_option(section, 'filename') and \
                config.get(section, 'filename') or section
            filename = os.path.normpath(
                os.path.join(configdir, filename))
            targetdir = config.has_option(section, 'targetdir') and \
                config.get(section, 'targetdir') or '.'
            targetdir = os.path.normpath(
                os.path.join(configdir, targetdir))
            print "Converting %s in %s" % (filename, targetdir)
            convert_odt(filename, targetdir, debug=options.debug,
                options={'download_source_link': options.download_source_link})
Example #2
0
    def _load_object_post_as_copy_conf(self, conf):
        if ('object_post_as_copy' in conf or '__file__' not in conf):
            # Option is explicitly set in middleware conf. In that case,
            # we assume operator knows what he's doing.
            # This takes preference over the one set in proxy app
            return

        cp = ConfigParser()
        if os.path.isdir(conf['__file__']):
            read_conf_dir(cp, conf['__file__'])
        else:
            cp.read(conf['__file__'])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name

        try:
            conf['object_post_as_copy'] = cp.get(proxy_section,
                                                 'object_post_as_copy')
        except (NoSectionError, NoOptionError):
            pass
Example #3
0
	def getMysqlConfig(self, db = 'test'):
		"""获取mysql连接配置

		- 依赖配置文件[conf/config.ini],节点[db]

		Returns:
			dbconfig dict.
		"""

		try:
			cf = ConfigParser()
			cf.read('conf/config.ini')
			dbconfig = {
				'host': cf.get('db', 'host'), 
				'port': cf.getint('db', 'port'), 
				'user': cf.get('db', 'user'), 
				'passwd': cf.get('db', 'passwd'), 
				'db': db
			}
			return dbconfig			
		except Exception as e:
			error = """Can't load config from [conf/config.ini] or [db] node doesn't exist.\n
			Please make sure this file."""
			logging.warning(error)
			print(error)
			raise Exception(e)
Example #4
0
 def _set_config_all(self, path_to_file):
     out = sys.stdout
     if not os.access(path_to_file, os.R_OK):
         self.log.warning( "cannot access file %s" % path_to_file )
         return
     elif not self.env.config:
         self.log.warning( "cannot access config file trac.ini" )
         return
     
     cfg = ConfigParser()
     cfg.read(path_to_file)
     
     if os.access(self.env.path, os.W_OK):
         path_to_trac_ini = os.path.join(self.env.path, 'conf', 'trac.ini')
         shutil.copy(path_to_trac_ini, path_to_trac_ini + '.bak')
         out.write( "created a backup of trac.ini to %s.bak" % path_to_trac_ini )
         out.write('\n')
     else:
         out.write( "could not create backup of trac.ini - continue anyway? [y|n] "  )
         input = sys.stdin.readline()
         if not input or not input.strip() == 'y':
             return
     
     for sect in cfg.sections():
         for opt in cfg.options(sect):
             self.config.set(sect, opt, cfg.get(sect, opt))
             out.write( "added config [%s] %s = %s" % (sect, opt, cfg.get(sect, opt)) )
             out.write('\n')
     self.config.save()
Example #5
0
    def get_value(self, section, option):
        """
        Retourne la valeur de l'option contenue dans la section passée en
        paramètre.
        """

        # On travaille sur le nom de la section parente
        # au cas où s'il s'agit d'une sous-section.
        parent_section = self.get_parent_section_name(section)


        # On vérifie d'abord que la section existe.
        if self.__spec_sections.has_key(parent_section):
            # Puis on récupère la spécification de la section.
            section_spec = self.__spec_sections.get(parent_section)
            option_type  = None

            # On parcours les options de la spécification à la recherche
            # du type de la valeur de l'option que l'on souhaite obtenir.
            for option_spec in section_spec[2]:
                if option_spec[0] == option:
                    option_type = option_spec[1]

            # Introuvable dans les options de la section ?
            # On regarde dans ceux de la sous-section si elle existe.
            if self.__spec_has_subsection(parent_section):
                for sub_option_spec in section_spec[3]:
                    if sub_option_spec[0] == option:
                        option_type = sub_option_spec[1]


            # On appelle la fonction qui va bien en fonction du type à obtenir.
            #
            # Les sous-sections héritent des options de leur section parente.
            # Si l'option n'existe pas dans la section, il doit sûrement s'agir
            # d'une sous-section. On cherche alors l'option dans la section
            # parente.
            if option_type == 'string':
                try:
                    return ConfigParser.get(self, section, option)
                except NoOptionError:
                    return ConfigParser.get(self, parent_section, option)

            if option_type == 'int':
                try:
                    return ConfigParser.getint(self, section, option)
                except NoOptionError:
                    return ConfigParser.getint(self, parent_section, option)

            if option_type == 'bool':
                try:
                    return ConfigParser.getboolean(self, section, option)
                except NoOptionError:
                    return ConfigParser.getboolean(self, parent_section, option)


            return None
        else:
            raise NameError("Invalid section name: '%(section)s'." % \
                            {'section': section})
def getVersionedFolderInfo(dirPath):
	"""
	returns a list containing the following information about the asset in dirPath:
	[0] last person to check it out, if locked
	[1] last person to check it in
	[2] time it was last checked in
	[3] latest comment on checkin
	[4] if it is isInstalled
	[5] filepath to install directory
	"""
	if not isVersionedFolder(dirPath):
		raise Exception("Not a versioned folder")
	
	nodeInfo = []
	cp = ConfigParser()
	cp.read(os.path.join(dirPath, ".nodeInfo"))
	if cp.getboolean("Versioning", "locked"):
		nodeInfo.append(cp.get("Versioning", "lastcheckoutuser"))
	else:
		nodeInfo.append("")
	nodeInfo.append(cp.get("Versioning", "lastcheckinuser"))
	nodeInfo.append(cp.get("Versioning", "lastcheckintime"))
	versionNum = int(cp.get("Versioning", "latestversion"))
	latestVersion = "v"+("%03d" % versionNum) 
	if cp.has_section("Comments"):
		nodeInfo.append(cp.get("Comments", latestVersion))
	else:
		nodeInfo.append('')
	if isInstalled(dirPath):
		nodeInfo.append("Yes")
		nodeInfo.append(glob.glob(os.path.join(dirPath, 'stable', '*stable*'))[0])
	else:
		nodeInfo.append("No")
		nodeInfo.append("")
	return nodeInfo
Example #7
0
def main(numthreads=10):
    t1 = time.time()
    queue = Queue()
    factory = TokenFactory()
    config = ConfigParser()
    config.read('vk_api.conf')

    url = API.get_url(
        app_id=config.get('api', 'id'), app_key=config.get('api', 'key'), 
        permissions=PERMISSIONS, redirect_uri=URI, display=DISPLAY, api_version=VERSION)

    # TODO: check token expiration
    token_pair = factory.get_token_pair()
    if not token_pair:
        token_pair = factory.store_token_pair(url)
    
    api = API(token=token_pair[0],user_id=token_pair[1])
    audio = api.audio
    data = audio.get

    if data:
        for item in data['response']['items']:
            queue.put(item)

        for i in range(numthreads):
            t = DownloadThread(queue, FILE_DIR)
            t.start()

        queue.join()


    t2 = time.time()
    print('Time: {0}'.format(t2-t1))
Example #8
0
def get_ws_call(action, payload, uid):
    """
    This function builds the url for the outgoing call to the different errata ws.
    :param payload: payload to be posted
    :param action: one of the 4 actions: create, update, close, retrieve
    :param uid: in case of a retrieve call, uid is needed
    :return: requests call
    """
    config = ConfigParser()
    config.read(os.path.join(os.getenv('ISSUE_CLIENT_HOME'), 'esgf-client.ini'))
    if action not in ACTIONS:
        logging.error('Unrecognized command, refer to the docs for help or use -h, error code: {}.'.format(6))
        sys.exit(1)

    url = config.get(WEBSERVICE, URL_BASE)+config.get(WEBSERVICE, action)
    if action in [CREATE, UPDATE]:
        r = requests.post(url, json.dumps(payload), headers=HEADERS)
    elif action == CLOSE:
        r = requests.post(url+uid)
    elif action == RETRIEVE:
        r = requests.get(url+uid)
    else:
        r = requests.get(url)
    if r.status_code != requests.codes.ok:
        logging.error('Errata WS call has failed, please refer to the error text for further information: {0}'
                      ', error code: {1}'.format(r.text, 5))
        sys.exit(1)
    return r
class NightscoutConfig(object):
    FILENAME = 'config'
    SECTION = 'NightscoutMenubar'
    HOST = 'nightscout_host'
    USE_MMOL = 'use_mmol'

    def __init__(self, app_name):
        self.config_path = os.path.join(rumps.application_support(app_name), self.FILENAME)
        self.config = ConfigParser()
        self.config.read([self.config_path])
        if not self.config.has_section(self.SECTION):
            self.config.add_section(self.SECTION)
        if not self.config.has_option(self.SECTION, self.HOST):
            self.set_host('')
        if not self.config.has_option(self.SECTION, self.USE_MMOL):
            self.set_use_mmol(False)

    def get_host(self):
        return self.config.get(self.SECTION, self.HOST)

    def set_host(self, host):
        self.config.set(self.SECTION, self.HOST, host)
        with open(self.config_path, 'w') as f:
            self.config.write(f)

    def get_use_mmol(self):
        return bool(self.config.get(self.SECTION, self.USE_MMOL))

    def set_use_mmol(self, mmol):
        self.config.set(self.SECTION, self.USE_MMOL, 'true' if mmol else '')
        with open(self.config_path, 'w') as f:
            self.config.write(f)
Example #10
0
def db_settings(backend=None):
    """
    Parses the contents of the db_settings.ini file and returns the connection
    settings of the required backend inside of a dictionary with the following
    keys:
      * backend
      * user
      * password
      * database
      * host (returned only by PostgreSQL backend)

    When backend is None the code looks for the value of the DATABASE environment
    variable. If the environment variable is not set Postgresql is going to be
    used as the default backend.
    """

    if not backend and os.getenv("DATABASE"):
        backend = os.getenv("DATABASE")
    elif not backend:
        backend = "postgresql"

    settings = {}

    config = ConfigParser()
    config.read(os.path.dirname(os.path.abspath(__file__)) + "/db_settings.ini")

    settings['backend']  = backend
    settings['user']     = config.get(backend, 'user')
    settings['password'] = config.get(backend, 'password')
    settings['database'] = config.get(backend, 'database')
    if backend == 'postgresql':
        settings['host'] = config.get(backend, 'host')

    return settings
Example #11
0
    def __init__(self, app, conf):
        self.app = app
        self.memcache_servers = conf.get("memcache_servers")
        serialization_format = conf.get("memcache_serialization_support")

        if not self.memcache_servers or serialization_format is None:
            path = os.path.join(conf.get("swift_dir", "/etc/swift"), "memcache.conf")
            memcache_conf = ConfigParser()
            if memcache_conf.read(path):
                if not self.memcache_servers:
                    try:
                        self.memcache_servers = memcache_conf.get("memcache", "memcache_servers")
                    except (NoSectionError, NoOptionError):
                        pass
                if serialization_format is None:
                    try:
                        serialization_format = memcache_conf.get("memcache", "memcache_serialization_support")
                    except (NoSectionError, NoOptionError):
                        pass

        if not self.memcache_servers:
            self.memcache_servers = "127.0.0.1:11211"
        if serialization_format is None:
            serialization_format = 2
        else:
            serialization_format = int(serialization_format)

        self.memcache = MemcacheRing(
            [s.strip() for s in self.memcache_servers.split(",") if s.strip()],
            allow_pickle=(serialization_format == 0),
            allow_unpickle=(serialization_format <= 1),
        )
Example #12
0
class Config(object):

    _raw_options = ("fetch_command", "player_command")
    _options = ("media_dir",)
    _expanduser = ("media_dir",)

    def __init__(self, my_file):
        my_file = os.path.expanduser(my_file)
        if not os.path.exists(my_file):
            with codecs.open(my_file, "w", encoding="utf-8") as fp:
                fp.write(config_file)
            raise MarrieError("Missing config file: %s. It will be created for you." % my_file)
        self._cp = ConfigParser()
        self._cp.read(my_file)
        for opt in self._raw_options + self._options:
            if not self._cp.has_option("config", opt):
                raise MarrieError("Missing needed config option: config:%s" % opt)

    def __getattr__(self, attr):
        opt = None
        if attr in self._raw_options:
            opt = self._cp.get("config", attr, True)
        elif attr in self._options:
            opt = self._cp.get("config", attr)
        elif attr == "podcast":
            opt = OrderedDict(self._cp.items("podcast"))
        if opt is None:
            raise AttributeError(attr)
        if attr in self._expanduser and not isinstance(opt, dict):
            return os.path.expanduser(opt)
        return opt
Example #13
0
    def _populate_config_from_old_location(self, conf):
        if ('rate_limit_after_segment' in conf or
                'rate_limit_segments_per_sec' in conf or
                'max_get_time' in conf or
                '__file__' not in conf):
            return

        cp = ConfigParser()
        if os.path.isdir(conf['__file__']):
            read_conf_dir(cp, conf['__file__'])
        else:
            cp.read(conf['__file__'])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name
        for setting in ('rate_limit_after_segment',
                        'rate_limit_segments_per_sec',
                        'max_get_time'):
            try:
                conf[setting] = cp.get(proxy_section, setting)
            except (NoSectionError, NoOptionError):
                pass
Example #14
0
def loadini(struct, configfile):
    """Load ini and store in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()

    fill_config_with_default_values(config, {
        "general": {
            "host": "irc.quakenet.org",
            "port": 6667,
            "channels": "#scibbytest",
            "nickname": "scabby",
            "plugins_directory": "~/dev/src/scibby-plugins"
        }})

    config.read(config_path)

    struct.host = config.get("general", "host")
    struct.port = config.getint("general", "port")
    struct.channels = config.get("general", "channels").split(",")
    struct.nickname = config.get("general", "nickname")
    struct.plugins_directory = config.get("general", "plugins_directory")

    return struct
Example #15
0
    def __init__(self, data_dir, configFile='glastopf.cfg'):
        if isinstance(configFile, ConfigParser):
            config = configFile
        else:
            config = ConfigParser()
            config.read(configFile)
        self.options = {'enabled': config.getboolean('taxii', 'enabled')}
        self.host = config.get('taxii', 'host')
        self.port = config.getint('taxii', 'port')
        self.inbox_path = config.get('taxii', 'inbox_path')
        self.use_https = config.getboolean('taxii', 'use_https')
        self.client = HttpClient()
        self.client.setProxy('noproxy')

        auth_credentials = {'username': config.get('taxii', 'auth_basic_username'),
                            'password': config.get('taxii', 'auth_basic_password'),
                            'key_file': config.get('taxii', 'auth_certificate_keyfile'),
                            'cert_file': config.get('taxii', 'auth_certificate_certfile')}
        self.client.setAuthCredentials(auth_credentials)

        if config.getboolean('taxii', 'use_auth_basic'):
            self.client.setAuthType(tc.HttpClient.AUTH_BASIC)
        elif config.getboolean('taxii', 'use_auth_certificate'):
            self.client.setAuthType(tc.HttpClient.AUTH_CERT)
        elif config.getboolean('taxii', 'use_auth_basic') and config.getboolean('taxii', 'use_auth_certificate'):
            self.client.setAuthType(tc.HttpClient.AUTH_CERT_BASIC)
        else:
            self.client.setAuthType(tc.HttpClient.AUTH_NONE)

        self.stix_transformer = StixTransformer(config, data_dir)
def _get_config():
    """Read configuration options from the ``jenkins_jobs.ini`` config file.

    Parse the ``jenkins_jobs.ini`` configuration file and return a dict in the
    following form::

        {
            'auth': ('username', 'password'),
            'url': …,
        }

    """
    config = ConfigParser()
    reader = config.readfp if version_info.major == 2 else config.read_file  # noqa pylint:disable=no-member
    with open(
        os.path.join(os.path.dirname(__file__), os.pardir, 'jenkins_jobs.ini')
    ) as handle:
        reader(handle)
    if version_info.major == 2:
        return {
            'auth': (
                config.get('jenkins', 'user'),
                config.get('jenkins', 'password')
            ),
            'url': config.get('jenkins', 'url'),
        }
    else:
        return {
            'auth': (config['jenkins']['user'], config['jenkins']['password']),
            'url': config['jenkins']['url'],
        }
Example #17
0
 def create_repositories_from_svn_config(self):
     logging.info("Reading configuration file %s" % self.config_file)
     config_parser = ConfigParser()
     config_parser.read(self.config_file)
     repositories = []
     for section in config_parser.sections():
         try:
             server = config_parser.get(section, 'server')
         except BaseException as e:
             logging.critical("Error while parsing config file %s\n%s" % (self.config_file, e))
             exit()
         if config_parser.has_option(section, 'user'):
             user = config_parser.get(section, 'user')
         else:
             user = None
         if config_parser.has_option(section, 'pass'):
             password = config_parser.get(section, 'pass')
         else:
             password = None
         repositories.append(SvnRepoMonitor(section, server, user, password, self.config_file))
         logging.info('Monitoring SVN repository %s (%s)' % (section, server))
     if repositories:
         return repositories
     else:
         logging.error("No sections in configuration file found. Aborting")
         exit()
Example #18
0
    def __init__(self, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
        self.data = {}
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr

        # Configuration import
        config = ConfigParser()
        config.readfp(open(CURRENT_DIR + "include/" + "mong.conf", "rb"))
        # Append to data stack

        # 		self.pidfile = config.get('Server', 'pidfile')

        # Database initialization
        host = config.get("Database", "host")
        user = config.get("Database", "user")
        passwd = config.get("Database", "passwd")
        dbname = config.get("Database", "dbname")
        db = dbApi(host, user, passwd, dbname)

        # Setting up the pid file
        pidfile = config.get("Server", "pidfile")
        self.pidfile = pidfile

        # Setting up the port for the telnet server
        port = config.get("Server", "port")
        self.port = int(port)

        # Append to data stack
        self.data["database"] = db
        self.data["config"] = config
        self.data["pidfile"] = pidfile
        self.data["port"] = port
Example #19
0
class ConfigReader(object):
    """
    为傲世堂的游戏项目配置文件定制的配置读取类。
    陈超写的arg.gameOption耦合性太强,只能在bible内使用。
    但是配置文件的结构设计的很合理。

    此类就是根据原来的结构设计重新写的解耦并且适用性更广的类。

    Example::

        conf = ConfigReader(game, region)
        ip = conf.get("mobile_www_ip")
        if conf.has_option("mobile_www_port")
            port = conf.getint("mobile_www_port")     
    """
    def __init__(self, game, section, conf_dir='/app/opbin/work/bible/conf'):
        self.game = game
        self.section = section
        self.conf_file = '{}/{}.conf'.format(conf_dir.rstrip('/'), self.game)
        self.config = ConfigParser()
        self.config.read(self.conf_file)
        self.has_section = self.config.has_section(self.section)

    def has_option(self, option):
        return self._has_option(self.section, option) or self._has_option('common', option)

    def _has_option(self, section, option):
        return self.config.has_option(section, option)

    def get(self, option, raw=0, var=None):
        if self._has_option(self.section, option):
            return self.config.get(self.section, option, raw, var)
        elif self._has_option('common', option):
            return self.config.get('common', option, raw, var)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getint(self, option):
        if self._has_option(self.section, option):
            return self.config.getint(self.section, option)
        elif self._has_option('common', option):
            return self.config.getint('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getfloat(self, option):
        if self._has_option(self.section, option):
            return self.config.getfloat(self.section, option)
        elif self._has_option('common', option):
            return self.config.getfloat('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getboolean(self, option):
        if self._has_option(self.section, option):
            return self.config.getboolean(self.section, option)
        elif self._has_option('common', option):
            return self.config.getboolean('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))
Example #20
0
def read_configuration(configuration_file):
    from ConfigParser import ConfigParser
    cp = ConfigParser()
    if configuration_file in cp.read([configuration_file]):
        db_location = cp.get("bot", "db_dir")
        token = cp.get("bot", "telegram_token")
        return YachBotConfiguration(db_location, token)
Example #21
0
    def start(self):
        from scheduler import Tree

        loog = self.addLog("stdio")
        self.pending = 0
        properties = self.build.getProperties()
        self.rendered_tree = tree = properties.render(self.treename)
        l10nbuilds = properties.render(self.l10nbuilds)
        cp = ConfigParser()
        cp.read(l10nbuilds)
        repo = cp.get(tree, "repo")
        branch = cp.get(tree, "mozilla")
        path = cp.get(tree, "l10n.ini")
        l10nbranch = cp.get(tree, "l10n")
        locales = cp.get(tree, "locales")
        if locales == "all":
            alllocales = "yes"
        else:
            alllocales = "no"
            properties.update({"locales": filter(None, locales.split())}, "Build")
        self.tree = Tree(self.rendered_tree, repo, branch, l10nbranch, path)
        loog.addStdout("Loading l10n.inis for %s\n" % self.rendered_tree)
        logger.debug(
            "scheduler.l10n.tree", "Loading l10n.inis for %s, alllocales: %s" % (self.rendered_tree, alllocales)
        )
        self.loadIni(repo, branch, path, alllocales)
Example #22
0
 def loadConfig(self):
     config = ConfigParser()
     configFilePath = os.path.join(os.path.dirname(__file__), "data", "config.cfg")
     config.read(configFilePath)
     self.setName(config.get("Info", "name"))
     self.setDescription(config.get("Info", "description"))
     self.setProject(config.get("Info", "project"))
def config():
    global video_format
    global resolution
    configr = ConfigParser()
    configr.read('settings.ini')
    quality = configr.get('SETTINGS', 'video_quality')
    qualities = {'android': ['107', '71'], '360p': ['106', '60'], '480p': ['106', '61'],
                 '720p': ['106', '62'], '1080p': ['108', '80'], 'highest': ['0', '0']}
    video_format = qualities[quality][0]
    resolution = qualities[quality][1]
    global lang
    global lang2
    lang = configr.get('SETTINGS', 'language')
    lang2 = configr.get('SETTINGS', 'language2')
    langd = {'Espanol_Espana': u'Español (Espana)', 'Francais': u'Français (France)', 'Portugues': u'Português (Brasil)',
            'English': u'English', 'Espanol': u'Español', 'Turkce': u'Türkçe', 'Italiano': u'Italiano',
            'Arabic': u'العربية', 'Deutsch': u'Deutsch'}
    lang = langd[lang]
    lang2 = langd[lang2]
    forcesub = configr.getboolean('SETTINGS', 'forcesubtitle')
    global forceusa
    forceusa = configr.getboolean('SETTINGS', 'forceusa')
    global localizecookies
    localizecookies = configr.getboolean('SETTINGS', 'localizecookies')
    onlymainsub = configr.getboolean('SETTINGS', 'onlymainsub')
    return [lang, lang2, forcesub, forceusa, localizecookies, quality, onlymainsub]
Example #24
0
    def __init__(self, config_filename):
        locale.setlocale(locale.LC_ALL, '')
        assert os.path.isfile(config_filename), "Config file not found"
        local_config_parser = ConfigParser()
        local_config_parser.read(config_filename)
        product_info_filename = local_config_parser.get("Config", "info_produtos")
        self._printer_name = local_config_parser.get("Config", "impressora")
        assert os.path.isfile(product_info_filename), "Product info file not found"
        # Set barcode filename
        self._barcode_filename = os.path.join(
            os.path.dirname(product_info_filename),
            "barcode"
        )

        cfg_parser = ConfigParser()
        cfg_parser.read(product_info_filename)

        self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC))
        self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC))

        if cfg_parser.has_section(self.PRICE_SEC):
            self.price_list = []
            for opt in sorted(cfg_parser.options(self.PRICE_SEC)):
                self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt))
        else:
            self.price_list = [1.7, 2.21]
        
        self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n")
        self._label_template = cfg_parser.get("Label", "label")
        self._labels_per_file = 30
        self._product_unity = "pç"
        self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")
Example #25
0
class Config(object):

    _raw_options = ('fetch_command', 'player_command')
    _options = ('media_dir',)
    _expanduser = ('media_dir',)

    def __init__(self, my_file):
        my_file = os.path.expanduser(my_file)
        if not os.path.exists(my_file):
            with codecs.open(my_file, 'w', encoding='utf-8') as fp:
                fp.write(config_file)
            raise MarrieError(
                'Missing config file: %s. It will be created for you.' % my_file)
        self._cp = ConfigParser()
        self._cp.read(my_file)
        for opt in (self._raw_options + self._options):
            if not self._cp.has_option('config', opt):
                raise MarrieError('Missing needed config option: config:%s' \
                                  % opt)

    def __getattr__(self, attr):
        opt = None
        if attr in self._raw_options:
            opt = self._cp.get('config', attr, True)
        elif attr in self._options:
            opt = self._cp.get('config', attr)
        elif attr == 'podcast':
            opt = OrderedDict(self._cp.items('podcast'))
        if opt is None:
            raise AttributeError(attr)
        if attr in self._expanduser and not isinstance(opt, dict):
            return os.path.expanduser(opt)
        return opt
Example #26
0
    def runTests(self,bundle=False):
        cp = ConfigParser()
        cp.read(os.path.join(path("config"), "test.cnf"))
        if self.opt.engine == "mozjs":
            engine = cp.get("mozjs", "command")
            nick = "mozjs"
        elif self.opt.engine == "v8":
            engine = cp.get("v8", "command")
            nick = "v8"
        elif self.opt.engine == "jsc":
            engine = cp.get("jsc", "command")
            nick = "jsc"
        else:
            engine = cp.get("rhino","command")
            nick = "rhino"
        bundleext = ""
        if bundle:
            bundleext = "-bundled"
        runpath = os.path.join(path("runners"), "%s%s.js" %(nick,bundleext))

        command = "%s %s" % (engine,runpath)
        ifh = sub.Popen(command,shell=True, stdout=sub.PIPE).stdout
        while 1:
            line = ifh.readline()
            if not line: break
            line = fixEndings(line)
            sys.stdout.write(line)
Example #27
0
def process_config(directory, config_file, sp):
	
	config = ConfigParser()
	config.read(config_file)
	sections = config.sections()
	
	db_or_element = db_or_element_format(sp, sections)
	
	if db_or_element == "db":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("db"))
	elif db_or_element == "element":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("element"))
	else:
		return "error"

	for s in sections:
		fname = config.get(s, "file_name")
		header = config.get(s, "header")
		if s in invalid_sections:
			if os.path.exists(directory + fname):
				os.remove(directory + fname)
		else:
			with open(directory + s + "_temp.txt", "w") as w:
				w.write(header + "\n")
				with open(directory + fname, "r") as r:
					for line in r:
						w.write(line)
				os.remove(directory + fname)
			os.rename(directory + s + "_temp.txt", directory + fname)
	os.remove(config_file)
	if len(invalid_sections) == 0:
		return None
	return {"invalid_sections":invalid_sections}
Example #28
0
 def validateSource(self):
     skip_to_pos = 0
     if os.path.exists(self.pickle):
         upfh = open(self.pickle, "rb")
         unpickler = Unpickler(upfh)
         old_opt,old_pos = unpickler.load()
         if self.opt == old_opt:
             skip_to_pos = old_pos
             for i in range(0,skip_to_pos,1):
                 sys.stdout.write(".")
     pos = -1
     files = self.files['humans'].keys()
     files.sort()
     cp = ConfigParser()
     cp.read(os.path.join(path("config"), "test.cnf"))
     validator_path = cp.get("validation", "validator")
     csl_schema_path = cp.get("validation", "schema")
     cslm_schema_path = cp.get("validation", "schema-m")
     for filename in files:
         pos += 1
         if pos < skip_to_pos: continue
         p = self.files['humans'][filename]
         test = CslTest(opt,p,filename,pos=pos)
         test.parse()
         test.validate(validator_path, csl_schema_path, cslm_schema_path)
     if os.path.exists( self.pickle ):
         os.unlink(self.pickle)
Example #29
0
File: api.py Project: akurz/cobbler
    def version(self, extended=False):
        """
        What version is cobbler?

        If extended == False, returns a float for backwards compatibility

        If extended == True, returns a dict:

            gitstamp      -- the last git commit hash
            gitdate       -- the last git commit date on the builder machine
            builddate     -- the time of the build
            version       -- something like "1.3.2"
            version_tuple -- something like [ 1, 3, 2 ]
        """
        config = ConfigParser()
        config.read("/etc/cobbler/version")
        data = {}
        data["gitdate"] = config.get("cobbler", "gitdate")
        data["gitstamp"] = config.get("cobbler", "gitstamp")
        data["builddate"] = config.get("cobbler", "builddate")
        data["version"] = config.get("cobbler", "version")
        # dont actually read the version_tuple from the version file
        data["version_tuple"] = []
        for num in data["version"].split("."):
            data["version_tuple"].append(int(num))

        if not extended:
            # for backwards compatibility and use with koan's comparisons
            elems = data["version_tuple"]
            return int(elems[0]) + 0.1 * int(elems[1]) + 0.001 * int(elems[2])
        else:
            return data
Example #30
0
def process_l10n_ini(inifile):
    """Read a Mozilla l10n.ini file and process it to find the localisation files
    needed by a project"""

    l10n = ConfigParser()
    l10n.readfp(open(path_neutral(inifile)))
    l10n_ini_path = os.path.dirname(inifile)

    for dir in l10n.get('compare', 'dirs').split():
        frompath = os.path.join(l10n_ini_path, l10n.get('general', 'depth'), dir, 'locales', 'en-US')
        if verbose:
            print '%s -> %s' % (frompath, os.path.join(l10ncheckout, 'en-US', dir))
        try:
            shutil.copytree(frompath, os.path.join(l10ncheckout, 'en-US', dir))
        except OSError:
            print 'ERROR: %s does not exist' % frompath

    try:
        for include in l10n.options('includes'):
            include_ini = os.path.join(
                l10n_ini_path, l10n.get('general', 'depth'), l10n.get('includes', include)
            )
            if os.path.isfile(include_ini):
                process_l10n_ini(include_ini)
    except TypeError:
        pass
    except NoSectionError:
        pass