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


Python dbm.open方法代码示例

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


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

示例1: find_test_run_time_diff

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def find_test_run_time_diff(test_id, run_time):
    times_db_path = os.path.join(os.path.join(os.getcwd(), '.testrepository'),
                                 'times.dbm')
    if os.path.isfile(times_db_path):
        try:
            test_times = dbm.open(times_db_path)
        except Exception:
            return False
        try:
            avg_runtime = float(test_times.get(str(test_id), False))
        except Exception:
            try:
                avg_runtime = float(test_times[str(test_id)])
            except Exception:
                avg_runtime = False

        if avg_runtime and avg_runtime > 0:
            run_time = float(run_time.rstrip('s'))
            perc_diff = ((run_time - avg_runtime) / avg_runtime) * 100
            return perc_diff
    return False 
开发者ID:openstack,项目名称:os-testr,代码行数:23,代码来源:subunit_trace.py

示例2: open

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def open(file, flag = 'r', mode = 0666):
    # guess the type of an existing database
    from whichdb import whichdb
    result=whichdb(file)
    if result is None:
        # db doesn't exist
        if 'c' in flag or 'n' in flag:
            # file doesn't exist and the new
            # flag was used so use default type
            mod = _defaultmod
        else:
            raise error, "need 'c' or 'n' flag to open new db"
    elif result == "":
        # db type cannot be determined
        raise error, "db type could not be determined"
    else:
        mod = __import__(result)
    return mod.open(file, flag, mode) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:anydbm.py

示例3: down

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def down(args):
    try:
        logout_url = open(LOGOUT_URL_FILE).read().strip()
    except FileNotFoundError:
        print("Connection seems to be down already. To connect, use 'nauta up'")
        return
    session = requests.Session()
    print("Logging out...")
    for error_count in range(10):
        try:
            r = session.get(logout_url)
            break
        except requests.RequestException:
            print("There was a problem logging out, retrying...")
            continue
    print(r.text)
    if 'SUCCESS' in r.text:
        os.remove(LOGOUT_URL_FILE) 
开发者ID:ateijelo,项目名称:nauta-cli,代码行数:20,代码来源:nauta.py

示例4: time_left

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def time_left(username, fresh=False, cached=False):
    now = time.time()
    with dbm.open(CARDS_DB, "c") as cards_db:
        card_info = json.loads(cards_db[username].decode())
        last_update = card_info.get('last_update', 0)
        password = card_info['password']
        if not cached:
            if (now - last_update > 60) or fresh:
                time_left = fetch_usertime(username)
                last_update = time.time()
                if re.match(r'[0-9:]+', time_left):
                    card_info['time_left'] = time_left
                    card_info['last_update'] = last_update
                    cards_db[username] = json.dumps(card_info)
        time_left = card_info.get('time_left', '-')
        return time_left 
开发者ID:ateijelo,项目名称:nauta-cli,代码行数:18,代码来源:nauta.py

示例5: ensure_config_yaml

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def ensure_config_yaml(plugin_manager):
    """
    Ensure we have a config.yaml present
    """
    # ensure config dir exists and is private
    for path in [CONFIG_DIR, os.path.join(CONFIG_DIR, 'jupyterhub_config.d')]:
        os.makedirs(path, mode=0o700, exist_ok=True)

    migrator.migrate_config_files()

    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, 'r') as f:
            config = yaml.load(f)
    else:
        config = {}

    hook = plugin_manager.hook
    hook.tljh_config_post_install(config=config)

    with open(CONFIG_FILE, 'w+') as f:
        yaml.dump(config, f) 
开发者ID:jupyterhub,项目名称:the-littlest-jupyterhub,代码行数:23,代码来源:installer.py

示例6: close

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def close(self):  # 关闭
        for db in self.open.values():
            db.close()
        self.open.clear()







###############################################################################
#                       全局变量定义 - 配置参数
###############################################################################

# Modul initialization    模块的初始化参数. 
开发者ID:hhstore,项目名称:annotated-py-bottle,代码行数:18,代码来源:bottle.py

示例7: keys

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def keys(self):
        """
        Return a list of usernames in the database.

        :rtype: list
        :returns: The usernames in the database.
        """
        if self.db == None:
            raise AssertionError("DB not open")

        self.lock.acquire()
        try:
            usernames = self.db.keys()
        finally:
            self.lock.release()
        usernames = [u for u in usernames if not u.startswith("--Reserved--")]
        return usernames 
开发者ID:scalyr,项目名称:scalyr-agent-2,代码行数:19,代码来源:basedb.py

示例8: reset_password

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def reset_password(self, username, new_password):
        """
        This allows changing the password of a logged user.
        """
        if not self._validate_password(new_password):
            login_err = (
                'Password too short! Please choose a password at least %d characters long.'
                % self.min_password_length
            )
            self.log.error(login_err)
            # Resetting the password will fail if the new password is too short.
            return login_err
        with dbm.open(self.dbm_path, 'c', 0o600) as db:
            db[username] = bcrypt.hashpw(new_password.encode(),
                                         bcrypt.gensalt())
        login_msg = "Your password has been changed successfully!"
        self.log.info(login_msg)
        return login_msg 
开发者ID:jupyterhub,项目名称:firstuseauthenticator,代码行数:20,代码来源:firstuseauthenticator.py

示例9: load_csv

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def load_csv(source,
             absolute_resolved_path,
             headers=False,
             dialect=None,
             encoding='utf-8-sig',
             **options):
    with open(absolute_resolved_path, 'r', newline='', encoding=encoding) as f:
        if dialect == "auto":
            sample = f.read(8192)
            f.seek(0)
            sniffer = csv.Sniffer()
            dialect = sniffer.sniff(sample)
        if headers:
            if dialect is None:
                r = csv.DictReader(f)
            else:
                r = csv.DictReader(f, dialect=dialect)
        else:
            if dialect is None:
                r = csv.reader(f)
            else:
                r = csv.reader(f, dialect=dialect)
        yield list(r) 
开发者ID:sphinx-contrib,项目名称:datatemplates,代码行数:25,代码来源:loaders.py

示例10: keys

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def keys(self):
        """Return a list of usernames in the database.

        @rtype: list
        @return: The usernames in the database.
        """
        if self.db == None:
            raise AssertionError("DB not open")

        self.lock.acquire()
        try:
            usernames = list(self.db.keys())
        finally:
            self.lock.release()
        usernames = [u for u in usernames if not u.startswith("--Reserved--")]
        return usernames 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:18,代码来源:BaseDB.py

示例11: test_071_anydbm

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def test_071_anydbm():                          # issue #71 {{{1
    import os
    if sys.version_info[0] == 2:
        import anydbm
    else:
        import dbm as anydbm
    # FIXME: determine path to sdcard. like: path = os.environ[""]
    del os.chmod
    for fname in (
        # failed: this is not SL4A application folder...
        # os.path.join("/data/data/com.googlecode.pythonforandroid",
        #              "files", "test_anydbm.dbm"),
        # OK: _chmod work well.
        # os.path.join("/data/local/abc", "test_anydbm.dbm"),
        # failed: _chmod not worked in FAT (SD card)
        os.path.join("/sdcard", "sl4a", "test_anydbm.dbm"),
    ):
        try:
            os.remove(fname + ".dat")
        except:
            pass
        anydbm.open(fname, "n")
        os.remove(fname + ".dat")
    return True 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:26,代码来源:test.py

示例12: test_107_large_file_report

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def test_107_large_file_report():               # issue #107 {{{1
    import os

    errors = []
    fname = "sample.bin"
    for n in (4294967294, 4294967297):
        fp = open(fname, "wb")
        fp.seek(n)
        fp.write("1".encode("utf-8"))
        fp.close()

        ans = os.path.getsize(fname)
        if ans != (n + 1):
            errors.append("%s(answer) vs %s(expected)" % (ans, n + 1))
        os.remove(fname)

    if not errors:
        return True
    print("can't get size collectly with %s" % str(errors))
    return False 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:22,代码来源:test.py

示例13: filter

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def filter(self, scanlines, header):
        """Filter out any scanlines that existed in the previous granule.

        Only works on datasets implementing get_dataname from the header.
        """
        dataname = self.ds.get_dataname(header, robust=True)
        if self._firstline_db is None:
            try:
                self._firstline_db = dbm.open(
                    str(self.granules_firstline_file), "r")
            except dbm.error as e: # presumably a lock
                tmpdir = tempfile.TemporaryDirectory()
                self._tmpdir = tmpdir # should be deleted only when object is
                tmp_gfl = str(pathlib.Path(tmpdir.name,
                    self.granules_firstline_file.name))
                logger.warning("Cannot read GFL DB at {!s}: {!s}, "
                    "presumably in use, copying to {!s}".format(
                        self.granules_firstline_file, e.args, tmp_gfl))
                shutil.copyfile(str(self.granules_firstline_file),
                    tmp_gfl)
                self.granules_firstline_file = tmp_gfl
                self._firstline_db = dbm.open(tmp_gfl)
        try:
            firstline = int(self._firstline_db[dataname])
        except KeyError as e:
            raise FilterError("Unable to filter firstline: {:s}".format(
                e.args[0])) from e
        if firstline > scanlines.shape[0]:
            logger.warning("Full granule {:s} appears contained in previous one. "
                "Refusing to return any lines.".format(dataname))
            return scanlines[0:0]
        return scanlines[scanlines["hrs_scnlin"] > firstline] 
开发者ID:atmtools,项目名称:typhon,代码行数:34,代码来源:filters.py

示例14: open

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def open(file, flag='r', mode=0666):
    """Open or create database at path given by *file*.

    Optional argument *flag* can be 'r' (default) for read-only access, 'w'
    for read-write access of an existing database, 'c' for read-write access
    to a new or existing database, and 'n' for read-write access to a new
    database.

    Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
    only if it doesn't exist; and 'n' always creates a new database.
    """

    # guess the type of an existing database
    from whichdb import whichdb
    result=whichdb(file)
    if result is None:
        # db doesn't exist
        if 'c' in flag or 'n' in flag:
            # file doesn't exist and the new
            # flag was used so use default type
            mod = _defaultmod
        else:
            raise error, "need 'c' or 'n' flag to open new db"
    elif result == "":
        # db type cannot be determined
        raise error, "db type could not be determined"
    else:
        mod = __import__(result)
    return mod.open(file, flag, mode) 
开发者ID:glmcdona,项目名称:meddle,代码行数:31,代码来源:anydbm.py

示例15: query

# 需要导入模块: import dbm [as 别名]
# 或者: from dbm import open [as 别名]
def query(self, word):
        from bs4 import BeautifulSoup
        sess = requests.Session()
        headers = {
            'Host': 'open.iciba.com',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate'
        }
        sess.headers.update(headers)
        url = 'http://open.iciba.com/huaci_new/dict.php?word=%s' % (word)
        try:
            resp = sess.get(url, timeout=100)
            text = resp.text
            pattern = r'(<div class=\\\"icIBahyI-group_pos\\\">[\s\S]+?</div>)'
            text = re.search(pattern, text).group(1)
        except:
            return None
        if (resp.status_code == 200) and (text):
            soup = BeautifulSoup(text, 'lxml')
            ps = soup.find_all('p')
            trans = []
            for item in ps:
                transText = item.get_text()
                transText = re.sub(
                    r'\s+', ' ', transText.replace('\t', '')).strip()
                if transText:
                    trans.append(transText)
            return '\n'.join(trans)
        else:
            return None 
开发者ID:caspartse,项目名称:python-translate,代码行数:34,代码来源:translate.py


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