本文整理汇总了Python中plumbum.local.path方法的典型用法代码示例。如果您正苦于以下问题:Python local.path方法的具体用法?Python local.path怎么用?Python local.path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类plumbum.local
的用法示例。
在下文中一共展示了local.path方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: patch_files
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def patch_files(self, filepatterns, data):
filepatterns = to_list(filepatterns)
directory = os.path.join(self.repo.working_dir, self.workingdir)
# cd into appropriate directory
with local.cwd(directory):
for pattern in filepatterns:
# Find files matching pattern in directory
# This is plumbum's syntax for shell globbing
path = local.path()
lp_files = path // str(pattern)
# Iterate and patch all files
for lp_file in lp_files:
filepath = str(lp_file)
self.patch_file(filepath, data)
示例2: make_artefact
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def make_artefact(self):
artefact = Artefact()
artefact.architecture = self.architecture
artefact.source = self.repo_info
artefact.build = self.build_result
# AVR
if self.architecture == 'avr':
target_hex = os.path.abspath(os.path.join(self.build_result['build_path'], self.build_result['TARGET_HEX']))
target_elf = os.path.abspath(os.path.join(self.build_result['build_path'], self.build_result['TARGET_ELF']))
artefact.name = os.path.splitext(os.path.basename(target_hex))[0]
artefact.binary.hex = file(target_hex, 'rb').read()
artefact.binary.elf = file(target_elf, 'rb').read()
# ESP
elif self.architecture == 'esp':
target_bin = os.path.abspath(self.build_result['TARGET_BIN'])
artefact.name = os.path.splitext(os.path.basename(target_bin))[0]
artefact.binary.bin = file(target_bin, 'rb').read()
return artefact
示例3: test_github
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def test_github(self, mock):
with open(pkg_resources.resource_filename('habitipy','apidoc.txt')) as f:
mock.return_value = f.read()
import builtins
lp = local.path(APIDOC_LOCAL_FILE)
Habitipy(None, from_github=True, branch='develop')
self.assertTrue(mock.called)
self.assertTrue(lp.exists())
with patch('builtins.open', MagicMock(wraps=builtins.open)) as mock:
Habitipy(None)
mock.assert_called_with(lp)
os.remove(lp)
Habitipy(None, from_github=True)
self.assertTrue(mock.called)
self.assertTrue(lp.exists())
with patch('builtins.open', MagicMock(wraps=builtins.open)) as mock:
Habitipy(None)
mock.assert_called_with(lp)
os.remove(lp)
示例4: _get
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def _get(self):
"""get content from server or cache"""
if Content._cache and not self._rebuild_cache:
return Content._cache
if not os.path.exists(CONTENT_JSON) or self._rebuild_cache:
content_endpoint = self._api.content.get
# pylint: disable=protected-access
server_lang = content_endpoint._node.params['query']['language']
Content._cache = content_endpoint(**next((
{'language': lang}
for lang in chain(
Content._lang_from_translation(),
Content._lang_from_locale())
if lang in server_lang.possible_values
), {})) # default
with open(CONTENT_JSON, 'w') as f:
json.dump(Content._cache, f)
return Content._cache
try:
with open(CONTENT_JSON) as f:
Content._cache = json.load(f)
return Content._cache
except JSONDecodeError:
self._rebuild_cache = True
return self._get()
示例5: run_makefile
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def run_makefile(self, makefile=None):
"""
Run the whole build process with designated Makefile.
"""
# cd into git repository directory
with local.cwd(self.repo.working_dir):
# cd into working directory inside git repository
with local.cwd(self.workingdir):
# Run Makefile to start the compilation process
make('--file', makefile, 'all-plus-firmware-info', stdout=self.stream, stderr=self.stream)
# Slurp output of build process
try:
self.stream.seek(0)
output = self.stream.read()
except IOError:
make_firmware_info = make['--file', makefile, 'firmware-info'] | grep['TARGET_']
output = make_firmware_info()
# Grep "TARGET_HEX", "TARGET_ELF" (for AVR) as well as "TARGET_BIN" and "TARGET_CHIP" (for ESP) paths
# from build output and store into "self.build_result"
target_matcher = re.compile('(?P<name>TARGET_.+):(?: (?P<value>.+))?')
for m in target_matcher.finditer(output):
match = m.groupdict()
name = match['name']
value = match['value']
if value:
self.build_result[name] = value
# Add build path to build result
self.build_result['build_path'] = pwd().strip()
示例6: __init__
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def __init__(self, api, rebuild_cache=False, path=None):
self._api = api
self._path = []
self._rebuild_cache = rebuild_cache
self._path = path
self._obj = None
self._resolve_path()
示例7: __init__
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def __init__(self, conf: Dict[str, str], *,
apis=None, current: Optional[List[str]] = None,
from_github=False, branch=None,
strict=False) -> None:
self._conf = conf
self._strict = strict
if isinstance(apis, (type(None), list)):
if not apis:
fn = local.path(APIDOC_LOCAL_FILE)
if not fn.exists():
fn = pkg_resources.resource_filename('habitipy', 'apidoc.txt')
fn = branch if from_github else fn
with warnings.catch_warnings():
warnings.simplefilter('error' if strict else 'ignore')
apis = parse_apidoc(fn, from_github)
with warnings.catch_warnings():
warnings.simplefilter('error' if strict else 'ignore')
apis = self._make_apis_dict(apis)
if isinstance(apis, ApiNode):
self._apis = apis
else:
raise TypeError('Possible apis {} have wrong type({})'.format(apis, type(apis)))
current = current or ['api', 'v3']
if not isinstance(current, list):
raise TypeError('Wrong current api position {}'.format(current))
_node = self._apis # type: Union[ApiNode, ApiEndpoint]
for part in current:
if isinstance(_node, ApiNode):
_node = _node.into(part)
else:
raise WrongPath("""Can't enter into {} with part {}""".format(_node, part))
self._node = _node
self._current = current
if isinstance(self._node, ApiEndpoint):
self.__doc__ = self._node.render_docstring()
示例8: validate
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def validate(self, obj):
"""check if obj has this api param"""
if self.path:
for i in self.path:
obj = obj[i]
obj = obj[self.field]
raise NotImplementedError('Validation is not implemented yet')
示例9: create_volume
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def create_volume(self):
"""Mkdir volumes if they don't exist yet.
Only apply to external volumes.
docker-compose up do not attemps to create it
so we have to do it ourselves"""
for service in self.project.services:
for volume in service.options.get('volumes', []):
if volume.external:
path = local.path(local.env.expand(volume.external))
if not path.exists():
logger.info(
"Create missing directory %s for service %s",
path, service.name)
path.mkdir()
示例10: __init__
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def __init__(self, service):
super(GenerateComposeFile, self).__init__()
# Do not use os.path.join()
self.service = service
resource_path = '../template/%s.docker-compose.yml' % service
template = pkg_resources.resource_stream(__name__, resource_path)
config = template.read()
self.config = yaml.safe_load(config)
示例11: _key_compose_file
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def _key_compose_file(self):
# create an (prod|dev).docker-compose.yml
# and set it in compose_file variable
# TODO: extract it
# TODO: create file properly
env_file = '%s.docker-compose.yml' % self._key_env()
if not local.path(env_file).exists():
(echo['version: "3"'] > env_file)()
return (
'docker-compose.yml:%s.docker-compose.yml'
% self._key_env())
示例12: get_traceback_formatter
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def get_traceback_formatter(default_root_path=None):
from plumbum import local
if default_root_path:
def relative(path):
r = local.path(path) - default_root_path
if r and r[0] != "..":
path = "./%s" % r
return path
default_root_path = local.path(default_root_path)
else:
relative = lambda path: path
def _format_list_iter(extracted_list):
extracted_list = list(extracted_list)
lines = []
for filename, lineno, name, line in extracted_list:
filename = relative(filename)
left = " {}:{} ".format(filename, lineno)
right = " {}".format(name)
lines.append((len(left)+len(right), left, right, line))
width = max(args[0] for args in lines) + 4
for _, left, right, line in lines:
item = left.ljust(width-len(right), ".") + right
if line:
item = item + ' >> {}'.format(line.strip())
yield item + '\n'
return _format_list_iter
示例13: __init__
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def __init__(self, remote_machine, server_class = "rpyc.utils.server.ThreadedServer", extra_setup = "", python_executable=None):
self.proc = None
self.tun = None
self.remote_machine = remote_machine
self._tmpdir_ctx = None
rpyc_root = local.path(rpyc.__file__).up()
self._tmpdir_ctx = remote_machine.tempdir()
tmp = self._tmpdir_ctx.__enter__()
copy(rpyc_root, tmp / "rpyc")
script = (tmp / "deployed-rpyc.py")
modname, clsname = server_class.rsplit(".", 1)
script.write(SERVER_SCRIPT.replace("$MODULE$", modname).replace("$SERVER$", clsname).replace("$EXTRA_SETUP$", extra_setup))
if python_executable:
cmd = remote_machine[python_executable]
else:
major = sys.version_info[0]
minor = sys.version_info[1]
cmd = None
for opt in ["python%s.%s" % (major, minor), "python%s" % (major,)]:
try:
cmd = remote_machine[opt]
except CommandNotFound:
pass
else:
break
if not cmd:
cmd = remote_machine.python
self.proc = cmd.popen(script, new_session = True)
line = ""
try:
line = self.proc.stdout.readline()
self.remote_port = int(line.strip())
except Exception:
try:
self.proc.terminate()
except Exception:
pass
stdout, stderr = self.proc.communicate()
raise ProcessExecutionError(self.proc.argv, self.proc.returncode, BYTES_LITERAL(line) + stdout, stderr)
if hasattr(remote_machine, "connect_sock"):
# Paramiko: use connect_sock() instead of tunnels
self.local_port = None
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 0))
self.local_port = s.getsockname()[1]
s.close()
self.tun = remote_machine.tunnel(self.local_port, self.remote_port)
示例14: load_conf
# 需要导入模块: from plumbum import local [as 别名]
# 或者: from plumbum.local import path [as 别名]
def load_conf(configfile, config=None):
"""Get authentication data from the AUTH_CONF file."""
default_login = 'your-login-for-api-here'
default_password = 'your-password-for-api-here'
config = config or {}
configfile = local.path(configfile)
if not configfile.exists():
configfile.dirname.mkdir()
else:
assert_secure_file(configfile)
with secure_filestore(), cli.Config(configfile) as conf:
config['url'] = conf.get('habitipy.url', 'https://habitica.com')
config['login'] = conf.get('habitipy.login', default_login)
config['password'] = conf.get('habitipy.password', default_password)
if config['login'] == default_login or config['password'] == default_password:
if cli.terminal.ask(
_("""Your creditentials are invalid. Do you want to enter them now?"""),
default=True):
msg = _("""
You can get your login information at
https://habitica.com/#/options/settings/api
Both your user id and API token should look like this:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
where 'x' is a number between 0-9 or a character a-f.
""")
print(dedent(msg))
msg = _("""Please enter your login (user ID)""")
config['login'] = cli.terminal.prompt(msg, validator=is_uuid)
msg = _("""Please enter your password (API token)""")
config['password'] = cli.terminal.prompt(msg, validator=is_uuid)
conf.set('habitipy.login', config['login'])
conf.set('habitipy.password', config['password'])
print(dedent(_("""
Your creditentials are securely stored in
{configfile}
You can edit that file later if you need.
""")).format(configfile=configfile))
config['show_numbers'] = conf.get('habitipy.show_numbers', 'y')
config['show_numbers'] = config['show_numbers'] in YES_ANSWERS
config['show_style'] = conf.get('habitipy.show_style', 'wide')
if config['show_style'] not in CHECK_MARK_STYLES:
config['show_style'] = 'wide'
return config