Python configparser.RawConfigParser() Examples

The following are 30 code examples of configparser.RawConfigParser(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module configparser , or try the search function .
Example #1
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #2
Source File: system_info.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #3
Source File: plugin_loader.py    From vt-ida-plugin with Apache License 2.0 6 votes vote down vote up
def read_config(self):
    """Read the user's configuration file."""

    logging.debug('[VT Plugin] Reading user config file: %s', self.vt_cfgfile)
    config_file = configparser.RawConfigParser()
    config_file.read(self.vt_cfgfile)

    try:
      if config_file.get('General', 'auto_upload') == 'True':
        self.auto_upload = True
      else:
        self.auto_upload = False
      return True
    except:
      logging.error('[VT Plugin] Error reading the user config file.')
      return False 
Example #4
Source File: cloud_connect_mod_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _load_options_from_inputs_spec(app_root, stanza_name):
    input_spec_file = 'inputs.conf.spec'
    file_path = op.join(app_root, 'README', input_spec_file)

    if not op.isfile(file_path):
        raise RuntimeError("README/%s doesn't exist" % input_spec_file)

    parser = configparser.RawConfigParser(allow_no_value=True)
    parser.read(file_path)
    options = list(parser.defaults().keys())
    stanza_prefix = '%s://' % stanza_name

    stanza_exist = False
    for section in parser.sections():
        if section == stanza_name or section.startswith(stanza_prefix):
            options.extend(parser.options(section))
            stanza_exist = True
    if not stanza_exist:
        raise RuntimeError("Stanza %s doesn't exist" % stanza_name)
    return set(options) 
Example #5
Source File: config.py    From linter-pylama with MIT License 6 votes vote down vote up
def _read_config(files):
        config = configparser.RawConfigParser()
        if isinstance(files, (str, type(u''))):
            files = [files]

        found_files = []
        for filename in files:
            try:
                found_files.extend(config.read(filename))
            except UnicodeDecodeError:
                LOG.exception("There was an error decoding a config file."
                              "The file with a problem was %s.",
                              filename)
            except configparser.ParsingError:
                LOG.exception("There was an error trying to parse a config "
                              "file. The file with a problem was %s.",
                              filename)
        return (config, found_files) 
Example #6
Source File: myconfig.py    From genmon with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, filename = None, section = None, simulation = False, log = None):

        super(MyConfig, self).__init__()
        self.log = log
        self.FileName = filename
        self.Section = section
        self.Simulation = simulation
        self.CriticalLock = threading.Lock()        # Critical Lock (writing conf file)
        self.InitComplete = False
        try:
            self.config = RawConfigParser()
            self.config.read(self.FileName)

            if self.Section == None:
                SectionList = self.GetSections()
                if len(SectionList):
                    self.Section = SectionList[0]

        except Exception as e1:
            self.LogErrorLine("Error in MyConfig:init: " + str(e1))
            return
        self.InitComplete = True
    #---------------------MyConfig::HasOption----------------------------------- 
Example #7
Source File: frontend.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def read(self, filenames, option_parser):
        if type(filenames) in (str, str):
            filenames = [filenames]
        for filename in filenames:
            try:
                # Config files must be UTF-8-encoded:
                fp = codecs.open(filename, 'r', 'utf-8')
            except IOError:
                continue
            try:
                if sys.version_info < (3,2):
                    CP.RawConfigParser.readfp(self, fp, filename)
                else:
                    CP.RawConfigParser.read_file(self, fp, filename)
            except UnicodeDecodeError:
                self._stderr.write(self.not_utf8_error % (filename, filename))
                fp.close()
                continue
            fp.close()
            self._files.append(filename)
            if self.has_section('options'):
                self.handle_old_config(filename)
            self.validate_settings(filename, option_parser) 
Example #8
Source File: cloud_connect_mod_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _load_options_from_inputs_spec(app_root, stanza_name):
    input_spec_file = 'inputs.conf.spec'
    file_path = op.join(app_root, 'README', input_spec_file)

    if not op.isfile(file_path):
        raise RuntimeError("README/%s doesn't exist" % input_spec_file)

    parser = configparser.RawConfigParser(allow_no_value=True)
    parser.read(file_path)
    options = list(parser.defaults().keys())
    stanza_prefix = '%s://' % stanza_name

    stanza_exist = False
    for section in parser.sections():
        if section == stanza_name or section.startswith(stanza_prefix):
            options.extend(parser.options(section))
            stanza_exist = True
    if not stanza_exist:
        raise RuntimeError("Stanza %s doesn't exist" % stanza_name)
    return set(options) 
Example #9
Source File: file_base.py    From keyrings.alt with MIT License 6 votes vote down vote up
def delete_password(self, service, username):
        """Delete the password for the username of the service.
        """
        service = escape_for_ini(service)
        username = escape_for_ini(username)
        config = configparser.RawConfigParser()
        if os.path.exists(self.file_path):
            config.read(self.file_path)
        try:
            if not config.remove_option(service, username):
                raise PasswordDeleteError("Password not found")
        except configparser.NoSectionError:
            raise PasswordDeleteError("Password not found")
        # update the file
        with open(self.file_path, 'w') as config_file:
            config.write(config_file) 
Example #10
Source File: srmdumps.py    From rucio with Apache License 2.0 6 votes vote down vote up
def generate_url(rse, config):
    '''
    :param rse: Name of the endpoint.
    :param config: RawConfigParser instance which may have configuration
    related to the endpoint.
    :returns: Tuple with the URL where the links can be queried to find new
    dumps and the pattern used to parse the date of the dump of the files/directories
    listed..
    '''
    site = rse.split('_')[0]
    if site not in config.sections():
        base_url = ddmendpoint_url(rse) + 'dumps'
        url_pattern = 'dump_%Y%m%d'
    else:
        url_components = config.get(site, rse).split('/')
        # The pattern may not be the last component
        pattern_index = next(idx for idx, comp in enumerate(url_components) if '%m' in comp)
        base_url = '/'.join(url_components[:pattern_index])
        url_pattern = '/'.join(url_components[pattern_index:])

    return base_url, url_pattern 
Example #11
Source File: file_base.py    From keyrings.alt with MIT License 6 votes vote down vote up
def _write_config_value(self, service, key, value):
        # ensure the file exists
        self._ensure_file_path()

        # load the keyring from the disk
        config = configparser.RawConfigParser()
        config.read(self.file_path)

        service = escape_for_ini(service)
        key = escape_for_ini(key)

        # update the keyring with the password
        if not config.has_section(service):
            config.add_section(service)
        config.set(service, key, value)

        # save the keyring back to the file
        with open(self.file_path, 'w') as config_file:
            config.write(config_file) 
Example #12
Source File: vcm.py    From vcm with GNU General Public License v3.0 6 votes vote down vote up
def write_global_vcm(self):
        print(f"Creating global config file with defaults in {GLOBAL_CONFIG_LOCATION}")

        global global_config
        global_config = configparser.RawConfigParser()
        global_config.add_section('GlobalSettings')

        global_config.set('GlobalSettings', 'openssl_binary', self.open_ssl_binary)

        global_config_file = os.path.expanduser(GLOBAL_CONFIG_LOCATION)

        with open(global_config_file, 'w') as configfile:
            try:
                global_config.write(configfile)
            except configparser.Error as ex:
                print(f"Error writing config file: {global_config_file} : {ex.message}")
                return 
Example #13
Source File: vcm.py    From vcm with GNU General Public License v3.0 6 votes vote down vote up
def write_project_vcm(self, project_name, local_folder, remote_folder, url_targets):
        project_config = configparser.RawConfigParser()
        project_config.add_section('ProjectSettings')
        project_config.set('ProjectSettings', 'project_name', project_name)
        project_config.set('ProjectSettings', 'local_path', os.path.join(local_folder, ''))
        project_config.set('ProjectSettings', 'remote_path', os.path.join(remote_folder, ''))
        project_config.set('ProjectSettings', 'url_targets', url_targets)

        project_vmc_filename = os.path.join(local_folder, '.vcm')

        with open(project_vmc_filename, 'w') as configfile:
            try:
                project_config.write(configfile)
            except configparser.Error as ex:
                print(f"Error writing config file: {project_vmc_filename} : {ex.message}")
                return 
Example #14
Source File: test_self.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_generate_config_disable_symbolic_names(self):
        # Test that --generate-rcfile puts symbolic names in the --disable
        # option.

        out = StringIO()
        self._run_pylint(["--generate-rcfile", "--rcfile="], out=out)

        output = out.getvalue()
        # Get rid of the pesky messages that pylint emits if the
        # configuration file is not found.
        master = re.search(r"\[MASTER", output)
        out = StringIO(output[master.start() :])
        parser = configparser.RawConfigParser()
        parser.read_file(out)
        messages = utils._splitstrip(parser.get("MESSAGES CONTROL", "disable"))
        assert "suppressed-message" in messages 
Example #15
Source File: file.py    From keyrings.alt with MIT License 6 votes vote down vote up
def _check_file(self):
        """
        Check if the file exists and has the expected password reference.
        """
        if not os.path.exists(self.file_path):
            return False
        self._migrate()
        config = configparser.RawConfigParser()
        config.read(self.file_path)
        try:
            config.get(
                escape_for_ini('keyring-setting'), escape_for_ini('password reference')
            )
        except (configparser.NoSectionError, configparser.NoOptionError):
            return False
        try:
            self._check_scheme(config)
        except AttributeError:
            # accept a missing scheme
            return True
        return self._check_version(config) 
Example #16
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #17
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def get_hosted_registry_insecure():
    """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
        registry is currently insecure.
    """
    hosted_registry_insecure = None
    if os.path.exists('/etc/sysconfig/docker'):
        try:
            ini_str = unicode('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
            ini_fp = io.StringIO(ini_str)
            config = ConfigParser.RawConfigParser()
            config.readfp(ini_fp)
            options = config.get('root', 'OPTIONS')
            if 'insecure-registry' in options:
                hosted_registry_insecure = True
        except:
            pass
    return hosted_registry_insecure 
Example #18
Source File: system_info.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #19
Source File: frontend.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def read(self, filenames, option_parser):
        if type(filenames) in (str, str):
            filenames = [filenames]
        for filename in filenames:
            try:
                # Config files must be UTF-8-encoded:
                fp = codecs.open(filename, 'r', 'utf-8')
            except IOError:
                continue
            try:
                if sys.version_info < (3,2):
                    CP.RawConfigParser.readfp(self, fp, filename)
                else:
                    CP.RawConfigParser.read_file(self, fp, filename)
            except UnicodeDecodeError:
                self._stderr.write(self.not_utf8_error % (filename, filename))
                fp.close()
                continue
            fp.close()
            self._files.append(filename)
            if self.has_section('options'):
                self.handle_old_config(filename)
            self.validate_settings(filename, option_parser) 
Example #20
Source File: system_info.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()
        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #21
Source File: legacy.py    From borgmatic with GNU General Public License v3.0 6 votes vote down vote up
def parse_configuration(config_filename, config_format):
    '''
    Given a config filename and an expected config file format, return the parsed configuration
    as a namedtuple with one attribute for each parsed section.

    Raise IOError if the file cannot be read, or ValueError if the format is not as expected.
    '''
    parser = RawConfigParser()
    if not parser.read(config_filename):
        raise ValueError('Configuration file cannot be opened: {}'.format(config_filename))

    validate_configuration_format(parser, config_format)

    # Describes a parsed configuration, where each attribute is the name of a configuration file
    # section and each value is a dict of that section's parsed options.
    Parsed_config = namedtuple(
        'Parsed_config', (section_format.name for section_format in config_format)
    )

    return Parsed_config(
        *(parse_section_options(parser, section_format) for section_format in config_format)
    ) 
Example #22
Source File: locator.py    From nxt-python with GNU General Public License v3.0 6 votes vote down vote up
def make_config(confpath=None):
    conf = configparser.RawConfigParser()
    if not confpath: confpath = os.path.expanduser('~/.nxt-python')
    print("Welcome to the nxt-python config file generator!")
    print("This function creates an example file which find_one_brick uses to find a brick.")
    try:
        if os.path.exists(confpath): input("File already exists at %s. Press Enter to overwrite or Ctrl+C to abort." % confpath)
    except KeyboardInterrupt:
        print("Not writing file.")
        return
    conf.add_section('Brick')
    conf.set('Brick', 'name', 'MyNXT')
    conf.set('Brick', 'host', '54:32:59:92:F9:39')
    conf.set('Brick', 'strict', 0)
    conf.set('Brick', 'method', 'usb=True, bluetooth=False')
    conf.write(open(confpath, 'w'))
    print("The file has been written at %s" % confpath)
    print("The file contains less-than-sane default values to get you started.")
    print("You must now edit the file with a text editor and change the values to match what you would pass to find_one_brick")
    print("The fields for name, host, and strict correspond to the similar args accepted by find_one_brick")
    print("The method field contains the string which would be passed to Method()")
    print("Any field whose corresponding option does not need to be passed to find_one_brick should be commented out (using a # at the start of the line) or simply removed.")
    print("If you have questions, check the wiki and then ask on the mailing list.") 
Example #23
Source File: system_info.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #24
Source File: system_info.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #25
Source File: system_info.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init__(self,
                  default_lib_dirs=default_lib_dirs,
                  default_include_dirs=default_include_dirs,
                  verbosity=1,
                  ):
        self.__class__.info = {}
        self.local_prefixes = []
        defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
                    'include_dirs': os.pathsep.join(default_include_dirs),
                    'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
                    'rpath': '',
                    'src_dirs': os.pathsep.join(default_src_dirs),
                    'search_static_first': str(self.search_static_first),
                    'extra_compile_args': '', 'extra_link_args': ''}
        self.cp = ConfigParser(defaults)
        self.files = []
        self.files.extend(get_standard_file('.numpy-site.cfg'))
        self.files.extend(get_standard_file('site.cfg'))
        self.parse_config_files()

        if self.section is not None:
            self.search_static_first = self.cp.getboolean(
                self.section, 'search_static_first')
        assert isinstance(self.search_static_first, int) 
Example #26
Source File: test_self.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_generate_config_disable_symbolic_names(self):
        # Test that --generate-rcfile puts symbolic names in the --disable
        # option.

        out = StringIO()
        self._run_pylint(["--generate-rcfile", "--rcfile="], out=out)

        output = out.getvalue()
        # Get rid of the pesky messages that pylint emits if the
        # configuration file is not found.
        master = re.search(r"\[MASTER", output)
        out = StringIO(output[master.start() :])
        parser = configparser.RawConfigParser()
        parser.read_file(out)
        messages = utils._splitstrip(parser.get("MESSAGES CONTROL", "disable"))
        assert "suppressed-message" in messages 
Example #27
Source File: stage1.py    From nekros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        parser = configparser.RawConfigParser()
        config_file = 'config.txt'
        parser.read(config_file)
                
        self.server =  parser.get('DB_CREDS', 'server')
        self.username =  parser.get('DB_CREDS', 'username')
        self.password =  parser.get('DB_CREDS', 'password')
        self.db_name =  parser.get('DB_CREDS', 'db_name') 
Example #28
Source File: analyzerfactory.py    From ee-outliers with GNU General Public License v3.0 5 votes vote down vote up
def create_multi(config_file, configparser_options={}):
        """
        Creates a list of analyzers based on a configuration file
        :param config_file: configuration file containing one or multiple analyzers
        :param configparser_options: Optional parameters to configparser.RawConfigParser(...)
        :return: returns the analyzer objects in a list
        """
        if not os.path.isfile(config_file):
            raise ValueError("Use case file %s does not exist" % config_file)

        # Read the ini file from disk
        config = configparser.RawConfigParser(**configparser_options)
        config.read(config_file)

        logging.logger.debug(config)

        # Create a list of all analyzers found in the config file
        analyzers = [AnalyzerFactory.section_to_analyzer(section_name, section)
                     for section_name, section in config.items()]
        analyzers = list(filter(None, analyzers))

        for analyzer in analyzers:
            if "whitelist_literals" in config.sections():
                for _, value in config["whitelist_literals"].items():
                    analyzer.model_whitelist_literals.append(
                        set([x.strip() for x in value.split(",")]))

            if "whitelist_regexps" in config.sections():
                for _, value in config["whitelist_regexps"].items():
                    analyzer.model_whitelist_regexps.append(
                        (set([re.compile(x.strip(), re.IGNORECASE) for x in value.split(",")])))

        return analyzers 
Example #29
Source File: main.py    From nekros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def after_stage_change_wallpaper(self, image_dir):
        parser = configparser.RawConfigParser()
        config_file = 'config.txt'
        parser.read(config_file)
        time_in_sec = parser.get('Time_Interval_TO_Change_Wallpaper', 'time_sec') #Retriving from config.txt
    
        change_wallpaper = changeWallpaper.ChangeWallpaper(image_dir)
        change_wallpaper.time_to_change_wallpaper(int(time_in_sec))    #Changing wallpaper after every given interval of time 
Example #30
Source File: netns_wrapper.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def filter_command(command, rootwrap_config):
    # Load rootwrap configuration
    try:
        rawconfig = ConfigParser.RawConfigParser()
        rawconfig.read(rootwrap_config)
        rw_config = wrapper.RootwrapConfig(rawconfig)
    except ValueError as exc:
        LOG.error('Incorrect value in %(config)s: %(exc)s',
                  {'config': rootwrap_config, 'exc': exc})
        sys.exit(errno.EINVAL)
    except ConfigParser.Error:
        LOG.error('Incorrect configuration file: %(config)s',
                  {'config': rootwrap_config})
        sys.exit(errno.EINVAL)

    # Check if command matches any of the loaded filters
    filters = wrapper.load_filters(rw_config.filters_path)
    try:
        wrapper.match_filter(filters, command, exec_dirs=rw_config.exec_dirs)
    except wrapper.FilterMatchNotExecutable as exc:
        LOG.error('Command %(command)s is not executable: '
                  '%(path)s (filter match = %(name)s)',
                  {'command': command,
                   'path': exc.match.exec_path,
                   'name': exc.match.name})
        sys.exit(errno.EINVAL)
    except wrapper.NoFilterMatched:
        LOG.error('Unauthorized command: %(cmd)s (no filter matched)',
                  {'cmd': command})
        sys.exit(errno.EPERM)