当前位置: 首页>>代码示例>>Python>>正文


Python ConfigParser.getboolean方法代码示例

本文整理汇总了Python中six.moves.configparser.ConfigParser.getboolean方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.getboolean方法的具体用法?Python ConfigParser.getboolean怎么用?Python ConfigParser.getboolean使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six.moves.configparser.ConfigParser的用法示例。


在下文中一共展示了ConfigParser.getboolean方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
  def load(self):
    schemes = [defaultScheme]
    parser = ConfigParser()
    parser.read(settings.DASHBOARD_CONF)

    for option, default_value in defaultUIConfig.items():
      if parser.has_option('ui', option):
        try:
          self.ui_config[option] = parser.getint('ui', option)
        except ValueError:
          self.ui_config[option] = parser.get('ui', option)
      else:
        self.ui_config[option] = default_value

    if parser.has_option('ui', 'automatic_variants'):
      self.ui_config['automatic_variants']   = parser.getboolean('ui', 'automatic_variants')
    else:
      self.ui_config['automatic_variants'] = True

    self.ui_config['keyboard_shortcuts'] = defaultKeyboardShortcuts.copy()
    if parser.has_section('keyboard-shortcuts'):
      self.ui_config['keyboard_shortcuts'].update( parser.items('keyboard-shortcuts') )

    for section in parser.sections():
      if section in ('ui', 'keyboard-shortcuts'):
        continue

      scheme = parser.get(section, 'scheme')
      fields = []

      for match in fieldRegex.finditer(scheme):
        field = match.group(1)
        if parser.has_option(section, '%s.label' % field):
          label = parser.get(section, '%s.label' % field)
        else:
          label = field

        fields.append({
          'name' : field,
          'label' : label
        })

      schemes.append({
        'name' : section,
        'pattern' : scheme,
        'fields' : fields,
      })

    self.schemes = schemes
开发者ID:aihua,项目名称:graphite-web,代码行数:51,代码来源:views.py

示例2: serve

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
def serve(args):
    config = ConfigParser({'port': '8080', 'db': None})
    config.read([CONFIG_FILE])

    port = int(args.port or int(config.get('app', 'port')))
    view_path = getattr(args, 'view_path', None)
    controller_path = getattr(args, 'controller_path', None)

    if args.cdn is None:
        if config.has_option('app', 'cdn'):
            cdn = config.getboolean('app', 'cdn')
        else:
            cdn = True
    else:
        cdn = args.cdn

    server.serve(db=config.get('app', 'db'), port=port, verbose=args.verbose,
                 view_path=view_path, controller_path=controller_path, cdn=cdn)
开发者ID:nehz,项目名称:avalon,代码行数:20,代码来源:cli.py

示例3: RepoConfiguration

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
class RepoConfiguration(object):
    """
    Read configuration from repository.
    """

    DEFAULT_CONFIG = dedent("""\
        [autorebuild]
        enabled = false
        """)

    def __init__(self, dir_path='', file_name=REPO_CONFIG_FILE):

        self._config_parser = ConfigParser()

        # Set default options
        self._config_parser.readfp(StringIO(self.DEFAULT_CONFIG))

        config_path = os.path.join(dir_path, file_name)
        if os.path.exists(config_path):
            self._config_parser.read(config_path)

    def is_autorebuild_enabled(self):
        return self._config_parser.getboolean('autorebuild', 'enabled')
开发者ID:vrutkovs,项目名称:osbs-client,代码行数:25,代码来源:repo_utils.py

示例4: SetupConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
class SetupConfig(object):
    """Wrapper around the setup.cfg file if available.

    One reason is to cleanup setup.cfg from these settings::

        [egg_info]
        tag_build = dev
        tag_svn_revision = true

    Another is for optional zest.releaser-specific settings::

        [zest.releaser]
        python-file-with-version = reinout/maurits.py


    """

    config_filename = SETUP_CONFIG_FILE

    def __init__(self):
        """Grab the configuration (overridable for test purposes)"""
        # If there is a setup.cfg in the package, parse it
        if not os.path.exists(self.config_filename):
            self.config = None
            return
        self.config = ConfigParser()
        with codecs.open(self.config_filename, 'r', 'utf8') as fp:
            self.config.readfp(fp)

    def development_marker(self):
        """Return development marker to be appended in postrelease

        Override the default ``.dev0`` in setup.cfg using
        a ``development-marker`` option::

            [zest.releaser]
            development-marker = .dev1

        Returns default of `.dev0` when nothing has been configured.

        """
        try:
            result = self.config.get('zest.releaser',
                                     'development-marker')
        except (NoSectionError, NoOptionError, ValueError):
            result = ".dev0"
        return result

    def has_bad_commands(self):
        if self.config is None:
            return False
        if not self.config.has_section('egg_info'):
            # bail out early as the main section is not there
            return False
        bad = False
        # Check 1.
        if self.config.has_option('egg_info', 'tag_build'):
            # Might still be empty.
            value = self.config.get('egg_info', 'tag_build')
            if value:
                logger.warn("%s has [egg_info] tag_build set to %r",
                            self.config_filename, value)
                bad = True
        # Check 2.
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            if self.config.getboolean('egg_info', 'tag_svn_revision'):
                value = self.config.get('egg_info', 'tag_svn_revision')
                logger.warn("%s has [egg_info] tag_svn_revision set to %r",
                            self.config_filename, value)
                bad = True
        return bad

    def fix_config(self):
        if not self.has_bad_commands():
            logger.warn("Cannot fix already fine %s.", self.config_filename)
            return
        if self.config.has_option('egg_info', 'tag_build'):
            self.config.set('egg_info', 'tag_build', '')
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            self.config.set('egg_info', 'tag_svn_revision', 'false')
        new_setup = open(self.config_filename, 'w')
        try:
            self.config.write(new_setup)
        finally:
            new_setup.close()
        logger.info("New setup.cfg contents:")
        print(''.join(open(self.config_filename).readlines()))

    def python_file_with_version(self):
        """Return Python filename with ``__version__`` marker, if configured.

        Enable this by adding a ``python-file-with-version`` option::

            [zest.releaser]
            python-file-with-version = reinout/maurits.py

        Return None when nothing has been configured.

        """
        default = None
#.........这里部分代码省略.........
开发者ID:drucci,项目名称:zest.releaser,代码行数:103,代码来源:pypi.py

示例5: PypiConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]

#.........这里部分代码省略.........
            server.strip() for server in raw_index_servers.split('\n')
            if server.strip() not in ignore_servers]
        return index_servers

    def want_release(self):
        """Does the user normally want to release this package.

        Some colleagues find it irritating to have to remember to
        answer the question "Check out the tag (for tweaks or
        pypi/distutils server upload)" with the non-default 'no' when
        in 99 percent of the cases they just make a release specific
        for a customer, so they always answer 'no' here.  This is
        where an extra config option comes in handy: you can influence
        the default answer so you can just keep hitting 'Enter' until
        zest.releaser is done.

        Either in your ~/.pypirc or in a setup.cfg in a specific
        package, add this when you want the default answer to this
        question to be 'no':

        [zest.releaser]
        release = no

        The default when this option has not been set is True.

        Standard config rules apply, so you can use upper or lower or
        mixed case and specify 0, false, no or off for boolean False,
        and 1, on, true or yes for boolean True.
        """
        default = True
        if self.config is None:
            return default
        try:
            result = self.config.getboolean('zest.releaser', 'release')
        except (NoSectionError, NoOptionError, ValueError):
            return default
        return result

    def extra_message(self):
        """Return extra text to be added to commit messages.

        This can for example be used to skip CI builds.  This at least
        works for Travis.  See
        http://docs.travis-ci.com/user/how-to-skip-a-build/

        Enable this mode by adding a ``extra-message`` option, either in the
        package you want to release, or in your ~/.pypirc::

            [zest.releaser]
            extra-message = [ci skip]
        """
        default = ''
        if self.config is None:
            return default
        try:
            result = self.config.get('zest.releaser', 'extra-message')
        except (NoSectionError, NoOptionError, ValueError):
            return default
        return result

    def create_wheel(self):
        """Should we create a Python wheel for this package?

        Either in your ~/.pypirc or in a setup.cfg in a specific
        package, add this when you want to create a Python wheel, next
        to a standard sdist:
开发者ID:drucci,项目名称:zest.releaser,代码行数:70,代码来源:pypi.py

示例6: SetupConfig

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
class SetupConfig(object):
    """Wrapper around the setup.cfg file if available.

    One reason is to cleanup setup.cfg from these settings::

        [egg_info]
        tag_build = dev
        tag_svn_revision = true

    Another is for optional zest.releaser-specific settings::

        [zest.releaser]
        no-input = yes


    """

    config_filename = SETUP_CONFIG_FILE

    def __init__(self):
        """Grab the configuration (overridable for test purposes)"""
        # If there is a setup.cfg in the package, parse it
        if not os.path.exists(os.path.join(utils.PACKAGE_ROOT, self.config_filename)):
            self.config = None
            return
        self.config = ConfigParser()
        with codecs.open(self.config_filename, 'r', 'utf8') as fp:
            self.config.readfp(fp)

    def has_bad_commands(self):
        if self.config is None:
            return False
        if not self.config.has_section('egg_info'):
            # bail out early as the main section is not there
            return False
        bad = False
        # Check 1.
        if self.config.has_option('egg_info', 'tag_build'):
            # Might still be empty.
            value = self.config.get('egg_info', 'tag_build')
            if value:
                logger.warn("%s has [egg_info] tag_build set to %r",
                            self.config_filename, value)
                bad = True
        # Check 2.
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            if self.config.getboolean('egg_info', 'tag_svn_revision'):
                value = self.config.get('egg_info', 'tag_svn_revision')
                logger.warn("%s has [egg_info] tag_svn_revision set to %r",
                            self.config_filename, value)
                bad = True
        return bad

    def fix_config(self):
        if not self.has_bad_commands():
            logger.warn("Cannot fix already fine %s.", self.config_filename)
            return
        if self.config.has_option('egg_info', 'tag_build'):
            self.config.set('egg_info', 'tag_build', '')
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            self.config.set('egg_info', 'tag_svn_revision', 'false')
        new_setup = open(self.config_filename, 'w')
        try:
            self.config.write(new_setup)
        finally:
            new_setup.close()
        logger.info("New setup.cfg contents:")
        print(''.join(open(self.config_filename).readlines()))

    def no_input(self):
        """Return whether the user wants to run in no-input mode.

        Enable this mode by adding a ``no-input`` option::

            [zest.releaser]
            no-input = yes

        The default when this option has not been set is False.

        Standard config rules apply, so you can use upper or lower or
        mixed case and specify 0, false, no or off for boolean False,
        and 1, on, true or yes for boolean True.
        """
        default = False
        if self.config is None:
            return default
        try:
            result = self.config.getboolean('zest.releaser', 'no-input')
        except (NoSectionError, NoOptionError, ValueError):
            return default
        return result

    def python_file_with_version(self):
        """Return Python filename with ``__version__`` marker, if configured.

        Enable this by adding a ``python-file-with-version`` option::

            [zest.releaser]
            python-file-with-version = reinout/maurits.py

#.........这里部分代码省略.........
开发者ID:blampe,项目名称:zest.releaser,代码行数:103,代码来源:pypi.py

示例7: loadini

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]

#.........这里部分代码省略.........
        }}

    default_keys_to_commands = dict((value, key) for (key, value)
                                    in iteritems(defaults['keyboard']))

    fill_config_with_default_values(config, defaults)
    if not config.read(config_path):
        # No config file. If the user has it in the old place then complain
        if os.path.isfile(os.path.expanduser('~/.bpython.ini')):
            sys.stderr.write("Error: It seems that you have a config file at "
                             "~/.bpython.ini. Please move your config file to "
                             "%s\n" % default_config_path())
            sys.exit(1)

    def get_key_no_doublebind(command):
        default_commands_to_keys = defaults['keyboard']
        requested_key = config.get('keyboard', command)

        try:
            default_command = default_keys_to_commands[requested_key]

            if (default_commands_to_keys[default_command] ==
                    config.get('keyboard', default_command)):
                setattr(struct, '%s_key' % default_command, '')
        except KeyError:
            pass

        return requested_key

    struct.config_path = config_path

    struct.dedent_after = config.getint('general', 'dedent_after')
    struct.tab_length = config.getint('general', 'tab_length')
    struct.auto_display_list = config.getboolean('general',
                                                 'auto_display_list')
    struct.syntax = config.getboolean('general', 'syntax')
    struct.arg_spec = config.getboolean('general', 'arg_spec')
    struct.paste_time = config.getfloat('general', 'paste_time')
    struct.single_undo_time = config.getfloat('general', 'single_undo_time')
    struct.highlight_show_source = config.getboolean('general',
                                                     'highlight_show_source')
    struct.hist_file = config.get('general', 'hist_file')
    struct.editor = config.get('general', 'editor')
    struct.hist_length = config.getint('general', 'hist_length')
    struct.hist_duplicates = config.getboolean('general', 'hist_duplicates')
    struct.flush_output = config.getboolean('general', 'flush_output')

    struct.pastebin_key = get_key_no_doublebind('pastebin')
    struct.copy_clipboard_key = get_key_no_doublebind('copy_clipboard')
    struct.save_key = get_key_no_doublebind('save')
    struct.search_key = get_key_no_doublebind('search')
    struct.show_source_key = get_key_no_doublebind('show_source')
    struct.suspend_key = get_key_no_doublebind('suspend')
    struct.toggle_file_watch_key = get_key_no_doublebind('toggle_file_watch')
    struct.undo_key = get_key_no_doublebind('undo')
    struct.reimport_key = get_key_no_doublebind('reimport')
    struct.up_one_line_key = get_key_no_doublebind('up_one_line')
    struct.down_one_line_key = get_key_no_doublebind('down_one_line')
    struct.cut_to_buffer_key = get_key_no_doublebind('cut_to_buffer')
    struct.yank_from_buffer_key = get_key_no_doublebind('yank_from_buffer')
    struct.clear_word_key = get_key_no_doublebind('clear_word')
    struct.backspace_key = get_key_no_doublebind('backspace')
    struct.clear_line_key = get_key_no_doublebind('clear_line')
    struct.clear_screen_key = get_key_no_doublebind('clear_screen')
    struct.delete_key = get_key_no_doublebind('delete')
开发者ID:daronwolff,项目名称:CHART_IN_REAL_TIME_socketio_python,代码行数:69,代码来源:config.py

示例8: Bot

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
class Bot(Client):
    def __init__(self, core, configfile):
        self.core = core

        self.configfile = configfile
        self.config = ConfigParser()
        self.config.read(configfile)
        
        host = self.config.get('base', 'host')
        port = self.config.getint('base', 'port')
        try:
            ssl = self.config.getboolean('base', 'ssl')
        except:
            ssl = False
        
        Client.__init__(self, (host, port), ssl)
        self.hooks = HookManager(self)
        self.plugins = PluginManager(self)

        self.hooks.install_owner(self)

        self.nick = None
        self.channels = {}
        superuser = self.config.get('base', 'superuser')
        self.allow_rules = {'*': {'ANY': 1}, superuser: {'ANY': 1000}}
        self.deny_rules = {}
        self._name = '_bot'

        autoload = self.config.get('base', 'autoload').split()
        for name in autoload:
            self.plugins.load(name)

        self.connect()

    def set_timer(self, fn, timestamp, owner=None):
        hook = TimestampHook(timestamp)
        hook.bind(fn, owner)
        self.hooks.install(hook)
        return hook

    def set_interval(self, fn, seconds, owner=None):
        hook = TimestampHook(time() + seconds, {'repeat': seconds})
        hook.bind(fn, owner)
        self.hooks.install(hook)
        return hook

    def set_timeout(self, fn, seconds, owner=None):
        hook = TimestampHook(time() + seconds)
        hook.bind(fn, owner)
        self.hooks.install(hook)
        return hook

    def do_tick(self, timestamp):
        self.hooks.call_timestamp(timestamp)

    def privmsg(self, target, text):
        wraplen = 510
        wraplen -= 1 + len(self.nick) # ":<nick>"
        wraplen -= 1 + 10 # "!<user>"
        wraplen -= 1 + 63 # "@<host>"
        wraplen -= 9 # " PRIVMSG "
        wraplen -= len(target) # "<target>"
        wraplen -= 2 # " :"
        for line in wrap(text, wraplen):
            self.send('PRIVMSG %s :%s' % (target, line))

    def notice(self, target, text):
        wraplen = 510
        wraplen -= 1 + len(self.nick) # ":<nick>"
        wraplen -= 1 + 10 # "!<user>"
        wraplen -= 1 + 63 # "@<host>"
        wraplen -= 8 # " NOTICE "
        wraplen -= len(target) # "<target>"
        wraplen -= 2 # " :"
        for line in wrap(text, wraplen):
            self.send('NOTICE %s :%s' % (target, line))

    def join(self, channels, keys=None):
        if isinstance(channels, str):
            channels = (channels,)
        if channels:
            channel_s = ','.join(channels)
            if keys:
                if isinstance(keys, str):
                    keys = (keys,)
                key_s = ','.join(keys)
                self.send('JOIN %s %s' % (channel_s, key_s))
                pairs = list(zip(channels, keys))
                for item in pairs:
                    self.channels[item[0]] = {'key': item[1], 'joined': False, 'nicks': set()}
            else:
                self.send('JOIN %s' % channel_s)
                for channel in channels:
                    self.channels[channel] = {'joined': False, 'nicks': set()}

    def part(self, channels, message=None):
        if type(channels) == str:
            channels = (channels,)
        if channels:
            channels = ','.join(channels)
#.........这里部分代码省略.........
开发者ID:jkent,项目名称:jkent-pybot,代码行数:103,代码来源:bot.py

示例9: ini_read

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
def ini_read(config_file):
    def strip_item(l):
        return [x.strip() for x in l]

    cfg = ConfigParser()
    cfg.read(config_file)
    log = {}
    log['file'] = cfg.get('log', 'file')
    log['level'] = cfg.getint('log', 'level')
    server = {}
    server['protocols'] = strip_item(cfg.get('server', 'protocols').split(','))
    server['listen_ip'] = cfg.get('server', 'listen_ip')
    server['listen_port'] = cfg.getint('server', 'listen_port')
    server['search'] = strip_item(cfg.get('server', 'search').split(','))
    server['allowed_hosts'] = strip_item(cfg.get('server', 'allowed_hosts').split(','))
    smartdns = {}
    smartdns['rules'] = []
    for rule in strip_item(cfg.get('smartdns', 'rules').split(',')):
        section = 'rules_' + rule
        smartdns['rules'].append({
            'name': rule,
            'url': cfg.get(section, 'url'),
            'proxy': cfg.getboolean(section, 'proxy'),
            'refresh': cfg.getint(section, 'refresh'),
            'dns': strip_item(cfg.get(section, 'dns').split(',')),
        })
    smartdns['hack_srv'] = strip_item(cfg.get('smartdns', 'hack_srv').split(','))
    section = 'bogus_nxdomain'
    smartdns['bogus_nxdomain'] = {
        'url': cfg.get(section, 'url'),
        'proxy': cfg.getboolean(section, 'proxy'),
        'refresh': cfg.getint(section, 'refresh'),
        'hack_ip': cfg.get(section, 'hack_ip'),
    }
    section = 'proxy'
    smartdns['proxy'] = {
        'type': cfg.get(section, 'type'),
        'ip': cfg.get(section, 'ip'),
        'port': cfg.getint(section, 'port'),
    }
    smartdns['upstreams'] = {}
    names = set()
    for rule in smartdns['rules']:
        names |= set(rule['dns'])
    for name in names:
        section = 'dns_' + name.strip()
        smartdns['upstreams'][name] = {
            'ip': cfg.get(section, 'ip').split(','),
            'port': cfg.getint(section, 'port'),
            'timeout': cfg.getint(section, 'timeout'),
            'proxy': cfg.getboolean(section, 'proxy'),
            'tcp': cfg.getboolean(section, 'tcp'),
            'priority': cfg.getint(section, 'priority'),
        }
    domains = []
    for name in strip_item(cfg.get('domains', 'domain').split(',')):
        section = 'domain_' + name
        domains.append({
            'name': cfg.get(section, 'name'),
            'url': cfg.get(section, 'url'),
            'proxy': cfg.getboolean(section, 'proxy'),
            'type': cfg.get(section, 'type'),
            'refresh': cfg.getint(section, 'refresh'),
        })
    config = {
        'log': log,
        'server': server,
        'smartdns': smartdns,
        'domains': domains,
    }
    return config
开发者ID:liuyug,项目名称:homedns,代码行数:73,代码来源:iniconfig.py

示例10: ConfigParser

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
# parser .ini file
try:
  cp = ConfigParser()
  cp.optionxform = str
  cp.readfp(open(inifile))
except:
  print("Error... problem parsing '%s' configuration file" % inifile, file=sys.stderr)
  sys.exit(1)

if opts.runpath is not None:
  cp.set('analysis', 'run_dir', opts.runpath)

# Check if we're running in automated mode or not
try:
  automated = cp.getboolean('analysis', 'autonomous')
except:
  automated = False

# Check if configuration file says to submit the DAG
submitdag = opts.condor_submit
if not submitdag:
  try:
    submitdag = cp.getboolean('analysis', 'submit_dag')
  except:
    submitdag = False

# Create DAG from ConfigParser object
dag = knope.knopeDAG(cp, inifile, pulsarlist=opts.pulsarlist)
if dag.error_code != 0: # check for any errors that occurred
  if dag.error_code in knope.KNOPE_ERROR.keys():
开发者ID:lscsoft,项目名称:lalsuite,代码行数:32,代码来源:lalapps_knope.py

示例11: Conf

# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import getboolean [as 别名]
class Conf(object):
    """Base class for Python-AD tests."""

    def __init__(self):
        fname = os.environ.get(
            'PYAD_TEST_CONFIG',
            os.path.join(os.path.dirname(__file__), 'test.conf.example')
        )
        if fname is None:
            raise Error('Python-AD test configuration file not specified.')
        if not os.path.exists(fname):
            raise Error('Python-AD test configuration file {} does not exist.'.format(fname))
        self.config = ConfigParser()
        self.config.read(fname)
        self.basedir = os.path.dirname(__file__)
        self._iptables = None
        self._domain = self.config.get('test', 'domain')
        self._tempfiles = []
        enable_logging()

        self.readonly_ad_creds = None
        readonly_env = os.environ.get('PYAD_READONLY_CONFIG', None)
        if readonly_env:
            bits = readonly_env.rsplit('@', 1)
            if len(bits) == 2:
                creds, domain = bits
                bits = creds.split(':', 1)
                if len(bits) == 2:
                    self._domain = domain
                    self.readonly_ad_creds = bits
        elif self.config.getboolean('test', 'readonly_ad_tests'):
            self.readonly_ad_creds = [
                config.get('test', 'ad_user_account'),
                config.get('test', 'ad_user_password'),
            ]

    def teardown(self):
        for fname in self._tempfiles:
            try:
                os.unlink(fname)
            except OSError:
                pass
        self._tempfiles = []

    def tempfile(self, contents=None, remove=False):
        fd, name = tempfile.mkstemp()
        if contents:
            os.write(fd, dedent(contents))
        elif remove:
            os.remove(name)
        os.close(fd)
        self._tempfiles.append(name)
        return name

    def read_file(self, fname):
        fname = os.path.join(self.basedir, fname)
        with open(fname, 'rb') as fin:
            buf = fin.read()

        return buf.decode('latin_1') if six.PY3 else buf

    def require(self, ad_user=False, local_admin=False, ad_admin=False,
                firewall=False, expensive=False):
        if firewall:
            local_admin = True
        config = self.config
        if ad_user and not (
            self.readonly_ad_creds and all(self.readonly_ad_creds)
        ):
            raise pytest.skip('test disabled by configuration')
        if local_admin:
            if not config.getboolean('test', 'intrusive_local_tests'):
                raise pytest.skip('test disabled by configuration')
            if not config.get('test', 'local_admin_account') or \
                    not config.get('test', 'local_admin_password'):
                raise pytest.skip('intrusive local tests enabled but no user/pw given')
        if ad_admin:
            if not config.getboolean('test', 'intrusive_ad_tests'):
                raise pytest.skip('test disabled by configuration')
            if not config.get('test', 'ad_admin_account') or \
                    not config.get('test', 'ad_admin_password'):
                raise pytest.skip('intrusive ad tests enabled but no user/pw given')
        if firewall and not self.iptables_supported:
            raise pytest.skip('iptables/conntrack not available')
        if expensive and not config.getboolean('test', 'expensive_tests'):
            raise pytest.skip('test disabled by configuration')

    def domain(self):
        return self._domain

    def ad_user_account(self):
        self.require(ad_user=True)
        return self.readonly_ad_creds[0]

    def ad_user_password(self):
        self.require(ad_user=True)
        return self.readonly_ad_creds[1]

    def local_admin_account(self):
        self.require(local_admin=True)
#.........这里部分代码省略.........
开发者ID:theatlantic,项目名称:python-active-directory,代码行数:103,代码来源:base.py


注:本文中的six.moves.configparser.ConfigParser.getboolean方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。