本文整理匯總了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
示例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)
示例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)
示例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
示例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)
示例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 模塊的初始化參數.
示例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
示例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
示例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)
示例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
示例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
示例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
示例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]
示例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)
示例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