本文整理汇总了Python中whichdb.whichdb函数的典型用法代码示例。如果您正苦于以下问题:Python whichdb函数的具体用法?Python whichdb怎么用?Python whichdb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了whichdb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
print "Pickle is available."
db = dumbdbm.open("dumbdb", "c")
db["1"] = "1"
db.close()
dbstr = whichdb.whichdb("dumbdb")
if dbstr:
print "Dumbdbm is available."
else:
print "Dumbdbm is not available."
db = dbhash.open("dbhash", "c")
db["1"] = "1"
db.close()
dbstr = whichdb.whichdb("dbhash")
if dbstr == "dbhash":
print "Dbhash is available."
else:
print "Dbhash is not available."
if bsddb is None:
dbstr = ""
else:
db = bsddb.hashopen("bsddb3", "c")
db["1"] = "1"
db.close()
dbstr = whichdb.whichdb("bsddb3")
if dbstr == "dbhash":
print "Bsddb[3] is available."
else:
print "Bsddb[3] is not available."
print
hammie = get_pathname_option("Storage", "persistent_storage_file")
use_dbm = options["Storage", "persistent_use_database"]
if not use_dbm:
print "Your storage %s is a: pickle" % (hammie,)
return
if not os.path.exists(hammie):
print "Your storage file does not exist yet."
return
db_type = whichdb.whichdb(hammie)
if db_type == "dbhash":
# could be dbhash or bsddb3
# only bsddb3 has a __version__ attribute - old bsddb module does not
if hasattr(bsddb, '__version__'):
try:
db = bsddb.hashopen(hammie, "r")
except bsddb.error:
pass
else:
db.close()
print "Your storage", hammie, "is a: bsddb[3]"
return
elif db_type is None:
print "Your storage %s is unreadable." % (hammie,)
print "Your storage %s is a: %s" % (hammie, db_type)
开发者ID:Xodarap,项目名称:Eipi,代码行数:59,代码来源:which_database.py
示例2: test_whichdb_name
def test_whichdb_name(self, name=name, mod=mod):
# Check whether whichdb correctly guesses module name
# for databases opened with module mod.
# Try with empty files first
f = mod.open(_fname, 'c')
f.close()
self.assertEqual(name, whichdb.whichdb(_fname))
# Now add a key
f = mod.open(_fname, 'w')
f["1"] = "1"
f.close()
self.assertEqual(name, whichdb.whichdb(_fname))
开发者ID:sephamorr,项目名称:8650linux,代码行数:12,代码来源:test_whichdb.py
示例3: main
def main():
"""Main function"""
# WRITE #######
db = gdbm.open('foo_gdbm', 'c')
db['one'] = 'un'
db['two'] = 'dos'
db['three'] = 'tres'
db.close()
# WHICH DBM ###
print "whichdb:", whichdb.whichdb('foo_gdbm')
print
# READ ########
db = gdbm.open('foo_gdbm', 'r')
# Iterate loop: first method (common to any dbm module)
for k in db.keys():
print k, ':', db[k]
# Iterate loop: second method (more efficient)
# The following code prints every key in the database db, without having to create a list in memory that contains them all.
k = db.firstkey()
while k != None:
print k, ':', db[k]
k = db.nextkey(k)
db.close()
开发者ID:jeremiedecock,项目名称:snippets,代码行数:34,代码来源:test_gdbm.py
示例4: main
def main():
"""Main function"""
# WRITE #######
db = anydbm.open('foo_anydbm', 'c')
db['one'] = 'un'
db['two'] = 'dos'
db['three'] = 'tres'
db.close()
# WHICH DBM ###
print "whichdb:", whichdb.whichdb('foo_anydbm')
print
# READ ########
db = anydbm.open('foo_anydbm', 'r')
# Iterate loop: first method (common to any dbm module)
for k in db.keys():
print k, ':', db[k]
# Iterate loop: second method (only dbhash and dumbdbm supports db.items())
for k, v in db.items():
print k, ':', v
db.close()
开发者ID:jeremiedecock,项目名称:snippets,代码行数:31,代码来源:test_anydbm.py
示例5: isDbUpToDate
def isDbUpToDate ( databaseFile ):
""" Check if index database is up to date """
upToDate = False
for dbFile in ( databaseFile + os.path.extsep + 'db', databaseFile ):
try:
if not os.path.exists(dbFile):
# Database doesn't exist, try next one
continue;
if not whichdb(dbFile):
# Not in a readable format
logger.debug ( 'Database not in a readable format: %s', dbFile );
break;
# From here, database exists and is readable
db = dbm.open(dbFile)
sourceFile = db["__source_path__"]
if not os.path.exists(sourceFile):
# Source file doesn't exist any more
break;
textFileSum = md5sum(sourceFile)
if textFileSum != db["__source_md5__"]:
logger.debug ( 'Source file checksum differs from the one used to build the database: %s', sourceFile );
db.close()
break;
if not db["__version__"] == Database.version:
logger.debug ( 'Database version "%s" doesn\'t match this version "%s"', db["__version__"], Database.version );
db.close()
break;
db.close()
# Everything is ok with the existing database
upToDate = True
break;
except Exception:
pass
return upToDate
开发者ID:GillesBouissac,项目名称:agentcluster,代码行数:34,代码来源:database.py
示例6: open
def open(file, flag = 'r', mode = 0666):
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result == "":
# Check if we have a 0-length file
statinfo = os.stat(file)
if statinfo.st_size == 0:
os.remove(file)
result = None
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: %s" % file
else:
mod = __import__(result)
return mod.open(file, flag, mode)
开发者ID:belenix,项目名称:belenixold,代码行数:25,代码来源:mydbm.py
示例7: open
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:0xcc,项目名称:pyston,代码行数:29,代码来源:anydbm.py
示例8: get_comment_db
def get_comment_db(songbook_path):
# check if this is the All songs songbook, if so don't do anything
if songbook_path == c.ALL_SONGS_PATH:
return dict()
comment_path = posixpath.splitext(songbook_path)[0] + '.comment'
# check if this is an old comment file -- we now use dumbdbm for portability
# upgrade done automatically TODO: this could be removed in the future
if whichdb.whichdb(comment_path) != 'dumbdbm':
# get a copy of the comments
old_shelf = shelve.open(comment_path)
comments = dict(old_shelf)
old_shelf.close()
# remove the old database file
files = glob.glob(comment_path+'*')
for f in files:
os.remove(f)
# write comments into dumbdbm shelf
new_shelf = shelve.Shelf(dumbdbm.open(comment_path))
for k in comments.keys():
new_shelf[k] = comments[k]
new_shelf.close() # close to make sure .comment file saved
# now assured of a dumbdbm shelf
return shelve.Shelf(dumbdbm.open(comment_path))
开发者ID:7flash,项目名称:yCanta,代码行数:28,代码来源:db.py
示例9: main
def main():
"""Main function"""
# WRITE #######
db = dbm.open('foo_dbm', 'c')
db['one'] = 'un'
db['two'] = 'dos'
db['three'] = 'tres'
db.close()
# WHICH DBM ###
print "whichdb:", whichdb.whichdb('foo_dbm')
print
# READ ########
db = dbm.open('foo_dbm', 'r')
for k in db.keys():
print k, ':', db[k]
db.close()
开发者ID:jeremiedecock,项目名称:snippets,代码行数:26,代码来源:test_dbm.py
示例10: showStatus
def showStatus (self):
try:
w = whichdb.whichdb(self.path)
except Exception:
w = None
g.es('whichdb is %s at %s'%(w, self.path))
开发者ID:leo-editor,项目名称:leo-editor-contrib,代码行数:8,代码来源:Library.py
示例11: _find_shelves
def _find_shelves(shelve_dir):
"""
Return the location of CMIP5 shelve files as a dictionary.
"""
_check_shelve_version(shelve_dir)
# Locations of shelve files
template = os.path.join(shelve_dir, TEMPLATE_SHELVE)
stdo = os.path.join(shelve_dir, STDO_SHELVE)
stdo_mip = os.path.join(shelve_dir, STDO_MIP_SHELVE)
assert whichdb(template)
assert whichdb(stdo)
assert whichdb(stdo_mip)
return dict(template=template, stdo=stdo, stdo_mip=stdo_mip)
开发者ID:ESGF,项目名称:esgf-drslib,代码行数:18,代码来源:init.py
示例12: test_anydbm_create
def test_anydbm_create(self):
# Verify that anydbm.open does *not* create a bsddb185 file
tmpdir = tempfile.mkdtemp()
try:
dbfile = os.path.join(tmpdir, "foo.db")
anydbm.open(dbfile, "c").close()
ftype = whichdb.whichdb(dbfile)
self.assertNotEqual(ftype, "bsddb185")
finally:
shutil.rmtree(tmpdir)
开发者ID:ChinaQuants,项目名称:pyston,代码行数:10,代码来源:test_bsddb185.py
示例13: validate_arguments
def validate_arguments(args):
"""
Validates passed arguments,
throws exception is something is wrong
"""
if not path.exists(args.config):
raise ValueError("Can not find application config: %s" % args.config)
if not whichdb(args.session):
raise ValueError("Can not find session storage file (%s), please, run \"install.py\" first" % args.session)
if not path.exists(args.file):
raise ValueError("Can not find file \"%s\" for backup" % args.file)
开发者ID:rosolovskiy,项目名称:backuper,代码行数:11,代码来源:backup.py
示例14: loadGiTaxBdb
def loadGiTaxBdb(self,inpFile):
import anydbm, whichdb
print whichdb.whichdb('/export/atovtchi/taxa.db')
gi2taxa = anydbm.open('/export/atovtchi/taxa.db', 'c')
inp = file(inpFile,'r')
iRow = 0
buff = {}
for line in inp:
(gi,taxid) = line.split()
buff[gi] = taxid
if iRow % 100000 == 0:
print gi, taxid, iRow
gi2taxa.update(buff)
buff = {}
iRow += 1
inp.close()
taxaCnt = {}
for (gi,taxid) in gi2taxa.iteritems():
taxaCnt[taxid] = taxaCnt.get(taxid,0) + 1
print sorted(((cnt,taxid) for (taxid,cnt) in taxaCnt.iteritems()))
开发者ID:andreyto,项目名称:mgtaxa,代码行数:20,代码来源:CollectTaxa.py
示例15: open
def open(db_name, mode):
if os.path.exists(db_name):
# let the file tell us what db to use
dbm_type = whichdb.whichdb(db_name)
else:
# fresh file - open with what the user specified
dbm_type = options["globals", "dbm_type"].lower()
f = open_funcs.get(dbm_type)
if f is None:
raise error("Unknown dbm type: %s" % dbm_type)
return f(db_name, mode)
开发者ID:ArildF,项目名称:rogie,代码行数:11,代码来源:dbmstorage.py
示例16: execute
def execute(self, opt_values, pos_args):
dep_file = opt_values['dep_file']
db_type = whichdb(dep_file)
print("DBM type is '%s'" % db_type)
if db_type in ('dbm', 'dbm.ndbm'): # pragma: no cover
raise InvalidCommand('ndbm does not support iteration of elements')
data = dbm.open(dep_file)
for key, value_str in dbm_iter(data):
value_dict = json.loads(value_str.decode('utf-8'))
value_fmt = pprint.pformat(value_dict, indent=4, width=100)
print("{key} -> {value}".format(key=key, value=value_fmt))
开发者ID:grnydawn,项目名称:VectorizeIt,代码行数:11,代码来源:cmd_dumpdb.py
示例17: init_cache
def init_cache(self):
if self.new_style_cache:
subliminal.region.configure('subzero.cache.file', expiration_time=datetime.timedelta(days=180),
arguments={'appname': "sz_cache",
'app_cache_dir': self.data_path},
replace_existing_backend=True)
Log.Info("Using new style file based cache!")
return
names = ['dbhash', 'gdbm', 'dbm']
dbfn = None
self.dbm_supported = False
# try importing dbm modules
if Core.runtime.os != "Windows":
impawrt = None
try:
impawrt = getattr(sys.modules['__main__'], "__builtins__").get("__import__")
except:
pass
if impawrt:
for name in names:
try:
impawrt(name)
except:
continue
if not self.dbm_supported:
self.dbm_supported = name
break
if self.dbm_supported:
# anydbm checks; try guessing the format and importing the correct module
dbfn = os.path.join(config.data_items_path, 'subzero.dbm')
db_which = whichdb(dbfn)
if db_which is not None and db_which != "":
try:
impawrt(db_which)
except ImportError:
self.dbm_supported = False
if self.dbm_supported:
try:
subliminal.region.configure('dogpile.cache.dbm', expiration_time=datetime.timedelta(days=30),
arguments={'filename': dbfn,
'lock_factory': MutexLock},
replace_existing_backend=True)
Log.Info("Using file based cache!")
return
except:
self.dbm_supported = False
Log.Warn("Not using file based cache!")
subliminal.region.configure('dogpile.cache.memory', replace_existing_backend=True)
开发者ID:plexinc-agents,项目名称:Sub-Zero.bundle,代码行数:54,代码来源:config.py
示例18: open_db
def open_db( self, fname, flag ):
"""Open the database, return a dictionary like object"""
shelf = None
# Some shelve implementations cannot be reopened
if not os.path.isfile( fname ):
shelf = shelve.open(filename=fname, flag=flag, protocol=2)
shelf.close()
dbtype = whichdb.whichdb( fname )
#log.info( 'database type: %s', dbtype )
shelf = shelve.open(filename=fname, flag=flag, protocol=2)
return shelf
开发者ID:blankenberg,项目名称:galaxy-central,代码行数:11,代码来源:db.py
示例19: info
def info(ctx, data):
'''
Display summary information about the DB
'''
print('DB Type:', whichdb(ctx.parent.params['db']))
print('Version:', data.get('_dbversion'))
print('Name :', data.get('name'))
print('Key :', data.get('_key'))
print("Count :", len(data))
print()
print('Location(s):')
pprint.pprint(data.get('_serial_libraries'))
开发者ID:exaile,项目名称:exaile,代码行数:12,代码来源:db_explorer.py
示例20: open
def open(file, flag = 'r', mode = 438):
from whichdb import whichdb
result = whichdb(file)
if result is None:
if 'c' in flag or 'n' in flag:
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == '':
raise error, 'db type could not be determined'
else:
mod = __import__(result)
return mod.open(file, flag, mode)
开发者ID:Pluckyduck,项目名称:eve,代码行数:13,代码来源:anydbm.py
注:本文中的whichdb.whichdb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论