本文整理汇总了Python中posixpath.expanduser函数的典型用法代码示例。如果您正苦于以下问题:Python expanduser函数的具体用法?Python expanduser怎么用?Python expanduser使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expanduser函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: initDB
def initDB(drop=False):
from elixir import metadata, setup_all, drop_all, create_all
from genericpath import exists
from os import makedirs
from posixpath import expanduser
DB_NAME = "stockflow.sqlite"
log = logging.getLogger(__name__)
log.info("Inicializando o Core")
dbpath = expanduser("~/.stockflow/")
if not exists(dbpath):
try:
makedirs(dbpath)
except OSError:
log.warning("Nao foi possivel criar os diretorios, \
usando o home do usuário.")
dbpath = expanduser("~")
metadata.bind = "".join(("sqlite:///", dbpath, DB_NAME))
metadata.bind.echo = False
setup_all()
if(drop):
drop_all()
if not exists("".join((dbpath, DB_NAME))) or drop:
log.debug("Criando tabelas...")
create_all()
开发者ID:rcoacci,项目名称:PyStockFlow,代码行数:30,代码来源:models.py
示例2: test_expanduser_home_envvar
def test_expanduser_home_envvar(self):
with support.EnvironmentVarGuard() as env:
env['HOME'] = '/home/victor'
self.assertEqual(posixpath.expanduser("~"), "/home/victor")
# expanduser() strips trailing slash
env['HOME'] = '/home/victor/'
self.assertEqual(posixpath.expanduser("~"), "/home/victor")
for home in '/', '', '//', '///':
with self.subTest(home=home):
env['HOME'] = home
self.assertEqual(posixpath.expanduser("~"), "/")
self.assertEqual(posixpath.expanduser("~/"), "/")
self.assertEqual(posixpath.expanduser("~/foo"), "/foo")
开发者ID:Eyepea,项目名称:cpython,代码行数:15,代码来源:test_posixpath.py
示例3: __setitem__
def __setitem__(self, key, value):
if key == "includes":
if isinstance(value, list):
value = value[0]
for path in split(value):
path = self._parser._interpolate("DEFAULT", None, path, self)
path = posixpath.expanduser(path)
if not posixpath.exists(path):
raise Exception, "No such configuration file: %s" % path
if posixpath.isdir(path):
logging.info("Parsing config filenames from directory: %s",
path)
def walk_func(arg, directory, names):
for name in names:
path = posixpath.join(directory, name)
if not posixpath.isdir(path):
arg._parser.read(path)
posixpath.walk(path, walk_func, self)
else:
logging.info("Parsing config filename: %s", path)
self._parser.read(path)
# Environment has precedence over configuration
elif not key.startswith("CHECKBOX") or key.upper() not in os.environ:
super(IncludeDict, self).__setitem__(key, value)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:26,代码来源:config.py
示例4: __init__
def __init__(self, path=None, expanduser=False):
super(Path, self).__init__()
path = posix.getcwdu() if path is None else path
self.value = posixpath.expanduser(path) if expanduser else path
self.create_methods()
self.parent = runtime.find("Object")
开发者ID:prologic,项目名称:mio,代码行数:8,代码来源:path.py
示例5: __call__
def __call__(cls, *args):
if args:
value = posixpath.expandvars(
posixpath.expanduser(
posixpath.join(*args)))
else:
value = str()
return value
开发者ID:alex-python,项目名称:chut,代码行数:8,代码来源:__init__.py
示例6: get_globals
def get_globals(script):
path = posixpath.expanduser(script)
if not posixpath.exists(path):
path = get_path(script)
if not path:
raise Exception, "Script not found in PATH: %s" % script
globals = {}
execfile(path, globals)
return globals
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:10,代码来源:script.py
示例7: FileNameReturnKey
def FileNameReturnKey(self, event):
from posixpath import isabs, expanduser, join
from string import strip
# if its a relative path then include the cwd in the name
name = strip(self.fileNameEntry.get())
if not isabs(expanduser(name)):
self.fileNameEntry.delete(0, 'end')
self.fileNameEntry.insert(0, join(self.cwd_print(), name))
self.okButton.flash()
self.OkPressed()
开发者ID:asottile,项目名称:ancient-pythons,代码行数:10,代码来源:filedlg.py
示例8: get_globals
def get_globals(script):
path = posixpath.expanduser(script)
if not posixpath.exists(path):
path = get_path(script)
if not path:
raise Exception("Script not found in PATH: %s" % script)
globals = {}
exec(compile(open(path).read(), path, 'exec'), globals)
return globals
开发者ID:brendan-donegan,项目名称:checkbox,代码行数:10,代码来源:script.py
示例9: __call__
def __call__(cls, *args, **kwargs):
if args:
value = posixpath.expandvars(
posixpath.expanduser(
posixpath.join(*args)))
else:
value = str()
if value and 'obj' in kwargs or 'object' in kwargs:
value = pathlib.Path(value)
return value
开发者ID:glehmann,项目名称:chut,代码行数:10,代码来源:__init__.py
示例10: __init__
def __init__(self, root, path=None, **kwargs):
self.root = root
htdocs_dir = self.root.config.get("htdocs_dir")
if htdocs_dir:
if htdocs_dir.strip() == "":
htdocs_dir = None
else:
htdocs_dir = posixpath.expanduser(htdocs_dir)
print htdocs_dir
self.path = (path or htdocs_dir or
pkg_resources.resource_filename("scrapyd", "frontend/site"))
print self.path
resource.Resource.__init__(self, **kwargs)
开发者ID:llonchj,项目名称:scrapyd,代码行数:13,代码来源:__init__.py
示例11: test_expanduser
def test_expanduser(self):
self.assertEqual(posixpath.expanduser("foo"), "foo")
try:
import pwd
except ImportError:
pass
else:
self.assertIsInstance(posixpath.expanduser("~/"), basestring)
# if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != "/":
self.assertEqual(posixpath.expanduser("~") + "/", posixpath.expanduser("~/"))
self.assertIsInstance(posixpath.expanduser("~root/"), basestring)
self.assertIsInstance(posixpath.expanduser("~foo/"), basestring)
with test_support.EnvironmentVarGuard() as env:
env["HOME"] = "/"
self.assertEqual(posixpath.expanduser("~"), "/")
开发者ID:herenowcoder,项目名称:stackless,代码行数:17,代码来源:test_posixpath.py
示例12: test_expanduser
def test_expanduser(self):
self.assertEqual(posixpath.expanduser("foo"), "foo")
try:
import pwd
except ImportError:
pass
else:
self.assert_(isinstance(posixpath.expanduser("~/"), basestring))
# if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != "/":
self.assertEqual(posixpath.expanduser("~") + "/", posixpath.expanduser("~/"))
self.assert_(isinstance(posixpath.expanduser("~root/"), basestring))
self.assert_(isinstance(posixpath.expanduser("~foo/"), basestring))
self.assertRaises(TypeError, posixpath.expanduser)
开发者ID:krattai,项目名称:xbmc-antiquated,代码行数:15,代码来源:test_posixpath.py
示例13: save
def save(self, filepath=None):
"""Save the persist to the given C{filepath}.
If None is specified, then the filename passed during construction will
be used.
"""
if filepath is None:
if self.filename is None:
return
filepath = self.filename
filepath = posixpath.expanduser(filepath)
if posixpath.isfile(filepath):
os.rename(filepath, filepath+".old")
dirname = posixpath.dirname(filepath)
if dirname and not posixpath.isdir(dirname):
os.makedirs(dirname)
self._backend.save(filepath, self._hardmap)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:17,代码来源:persist.py
示例14: create_application
def create_application(self, args=sys.argv):
# Create data directory
data_directory = get_variable("CHECKBOX_DATA", ".")
safe_make_directory(data_directory)
# Prepend environment options
string_options = get_variable("CHECKBOX_OPTIONS", "")
args[:0] = split(string_options)
(options, args) = self.parse_options(args)
# Replace shorthands
for shorthand in "blacklist", "blacklist_file", "whitelist", "whitelist_file":
key = ".*/jobs_info/%s" % shorthand
value = getattr(options, shorthand)
if value:
options.config.append("=".join([key, value]))
# Set logging early
set_logging(options.log_level, options.log)
# Config setup
if len(args) != 2:
sys.stderr.write(_("Missing configuration file as argument.\n"))
sys.exit(1)
config = Config()
config_filename = posixpath.expanduser(args[1])
config.read_filename(config_filename)
config.read_configs(options.config)
section_name = "checkbox/plugins/client_info"
section = config.get_section(section_name)
if not section:
section = config.add_section(section_name)
section.set("name", posixpath.basename(args[1]) \
.replace(".ini", ""))
section.set("version", config.get_defaults().version)
# Check options
if options.version:
print(config.get_defaults().version)
sys.exit(0)
return self.application_factory(config)
开发者ID:brendan-donegan,项目名称:checkbox,代码行数:44,代码来源:application.py
示例15: terminfo
def terminfo( term=None, binary=False, encoding=None ) :
"""
Returns a TermInfo structure for the terminal specified.
The `binary` parameter controls whether the resulting object
has its capabilities represented as latin1-encoded `bytes`
objects or as `str` objects. The former is strictly more
correct, but can be a bit painful to use. A few terminfo
entries representing more obscure hardware can cause utf
encoding errors in the `binary=False` mode, but modern stuff
is generally fine. The `encoding` parameter is used for
handling of string parameters in processing of format-string
capabilities.
"""
key = (term,binary,encoding)
info = _cache.get( key )
if info is None :
if term is None :
term = os.environ[ 'TERM' ]
if encoding is None :
encoding = _default_encoding
path = None
entry = _null_entry
if term != 'null' :
suffix = term[0]
if sys.platform == 'darwin' :
suffix = '%02X' % ord( suffix )
suffix += '/' + term
path = posixpath.expanduser( '~/.terminfo/' + suffix )
if not os.path.exists( path ) :
path = '/usr/share/terminfo/' + suffix
info = make_terminfo_from_path( path, binary, encoding )
_cache[ (term,binary,encoding) ] = info
_cache[ key ] = info
return info
开发者ID:zachariahreed,项目名称:pyterminfo,代码行数:44,代码来源:__init__.py
示例16: __init__
def __init__(self, home=None):
if not home:
home = expanduser('~/.%s' % NAME)
self.home = home
if not path.exists(self.home):
mkdir(self.home)
self.fields = [
Field('Album', 'album', 'album', Field.SET_IF_EMPTY),
Field('Artist', 'artist.name', 'artist', Field.IGNORE),
Field('Label', 'label.name', 'grouping', Field.SET_IF_EMPTY),
Field('Long Description', 'notes', 'long description', Field.SET_IF_EMPTY),
Field('Genre', 'genres[0]', 'genre', Field.SET_IF_EMPTY),
Field('Released', 'released', 'released', Field.SET_IF_EMPTY),
Field('Title', 'title', 'name', Field.IGNORE),
Field('Track Number', 'track number', 'track number', Field.SET_IF_EMPTY),
Field('Year', 'year', 'year', Field.SET_IF_EMPTY)
]
开发者ID:jdolan,项目名称:itunes-discogs,代码行数:19,代码来源:config.py
示例17: test_expanduser
def test_expanduser(self):
self.assertEqual(posixpath.expanduser("foo"), "foo")
try:
import pwd
except ImportError:
pass
else:
self.assert_(isinstance(posixpath.expanduser("~/"), basestring))
# if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != '/':
self.assertEqual(
posixpath.expanduser("~") + "/",
posixpath.expanduser("~/")
)
self.assert_(isinstance(posixpath.expanduser("~root/"), basestring))
self.assert_(isinstance(posixpath.expanduser("~foo/"), basestring))
with test_support.EnvironmentVarGuard() as env:
env.set('HOME', '/')
self.assertEqual(posixpath.expanduser("~"), "/")
self.assertRaises(TypeError, posixpath.expanduser)
开发者ID:Vignesh2736,项目名称:IncPy,代码行数:22,代码来源:test_posixpath.py
示例18: load
def load(self, filepath):
filepath = posixpath.expanduser(filepath)
if not posixpath.isfile(filepath):
raise PersistError("File not found: %s" % filepath)
if posixpath.getsize(filepath) == 0:
return
try:
self._hardmap = self._backend.load(filepath)
except:
filepathold = filepath+".old"
if (posixpath.isfile(filepathold) and
posixpath.getsize(filepathold) > 0):
# warning("Broken configuration file at %s" % filepath)
# warning("Trying backup at %s" % filepathold)
try:
self._hardmap = self._backend.load(filepathold)
except:
raise PersistError("Broken configuration file at %s" %
filepathold)
else:
raise PersistError("Broken configuration file at %s" %
filepath)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:22,代码来源:persist.py
示例19: path_expand
def path_expand(path):
path = posixpath.expanduser(path)
return glob(path)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:3,代码来源:path.py
示例20: test_expanduser_pwd
def test_expanduser_pwd(self):
pwd = support.import_module('pwd')
self.assertIsInstance(posixpath.expanduser("~/"), str)
self.assertIsInstance(posixpath.expanduser(b"~/"), bytes)
# if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != '/':
self.assertEqual(
posixpath.expanduser("~") + "/",
posixpath.expanduser("~/")
)
self.assertEqual(
posixpath.expanduser(b"~") + b"/",
posixpath.expanduser(b"~/")
)
self.assertIsInstance(posixpath.expanduser("~root/"), str)
self.assertIsInstance(posixpath.expanduser("~foo/"), str)
self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes)
self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes)
with support.EnvironmentVarGuard() as env:
# expanduser should fall back to using the password database
del env['HOME']
home = pwd.getpwuid(os.getuid()).pw_dir
# $HOME can end with a trailing /, so strip it (see #17809)
home = home.rstrip("/") or '/'
self.assertEqual(posixpath.expanduser("~"), home)
# bpo-10496: If the HOME environment variable is not set and the
# user (current identifier or name in the path) doesn't exist in
# the password database (pwd.getuid() or pwd.getpwnam() fail),
# expanduser() must return the path unchanged.
with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError), \
mock.patch.object(pwd, 'getpwnam', side_effect=KeyError):
for path in ('~', '~/.local', '~vstinner/'):
self.assertEqual(posixpath.expanduser(path), path)
开发者ID:Eyepea,项目名称:cpython,代码行数:38,代码来源:test_posixpath.py
注:本文中的posixpath.expanduser函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论