本文整理汇总了Python中xonsh.environ.locate_binary函数的典型用法代码示例。如果您正苦于以下问题:Python locate_binary函数的具体用法?Python locate_binary怎么用?Python locate_binary使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了locate_binary函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resolve_binary_loc
def resolve_binary_loc(self):
"""Sets the binary location"""
alias = self.alias
if alias is None:
binary_loc = locate_binary(self.cmd[0])
elif callable(alias):
binary_loc = None
else:
binary_loc = locate_binary(alias[0])
self.binary_loc = binary_loc
示例2: test_locate_binary_on_windows
def test_locate_binary_on_windows():
files = ('file1.exe', 'FILE2.BAT', 'file3.txt')
with TemporaryDirectory() as tmpdir:
for fname in files:
fpath = os.path.join(tmpdir, fname)
with open(fpath, 'w') as f:
f.write(fpath)
env = Env({'PATH': [tmpdir], 'PATHEXT': ['.COM', '.EXE', '.BAT']})
with mock_xonsh_env(env):
assert_equal( locate_binary('file1'), os.path.join(tmpdir,'file1.exe'))
assert_equal( locate_binary('file1.exe'), os.path.join(tmpdir,'file1.exe'))
assert_equal( locate_binary('file2'), os.path.join(tmpdir,'FILE2.BAT'))
assert_equal( locate_binary('file2.bat'), os.path.join(tmpdir,'FILE2.BAT'))
assert_equal( locate_binary('file3'), None)
示例3: test_locate_binary_on_windows
def test_locate_binary_on_windows(xonsh_builtins):
files = ("file1.exe", "FILE2.BAT", "file3.txt")
with TemporaryDirectory() as tmpdir:
for fname in files:
fpath = os.path.join(tmpdir, fname)
with open(fpath, "w") as f:
f.write(fpath)
xonsh_builtins.__xonsh__.env.update(
{"PATH": [tmpdir], "PATHEXT": [".COM", ".EXE", ".BAT"]}
)
xonsh_builtins.__xonsh__.commands_cache = CommandsCache()
assert locate_binary("file1") == os.path.join(tmpdir, "file1.exe")
assert locate_binary("file1.exe") == os.path.join(tmpdir, "file1.exe")
assert locate_binary("file2") == os.path.join(tmpdir, "FILE2.BAT")
assert locate_binary("file2.bat") == os.path.join(tmpdir, "FILE2.BAT")
assert locate_binary("file3") is None
示例4: test_locate_binary_on_windows
def test_locate_binary_on_windows(xonsh_builtins):
files = ('file1.exe', 'FILE2.BAT', 'file3.txt')
with TemporaryDirectory() as tmpdir:
for fname in files:
fpath = os.path.join(tmpdir, fname)
with open(fpath, 'w') as f:
f.write(fpath)
xonsh_builtins.__xonsh_env__.update({
'PATH': [tmpdir],
'PATHEXT': ['.COM', '.EXE', '.BAT'],
})
assert locate_binary('file1') == os.path.join(tmpdir,'file1.exe')
assert locate_binary('file1.exe') == os.path.join(tmpdir,'file1.exe')
assert locate_binary('file2') == os.path.join(tmpdir,'FILE2.BAT')
assert locate_binary('file2.bat') == os.path.join(tmpdir,'FILE2.BAT')
assert locate_binary('file3') is None
示例5: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh_env__
encoding = env.get('XONSH_ENCODING')
errors = env.get('XONSH_ENCODING_ERRORS')
for i, fname in enumerate(args):
fpath = fname
if not os.path.isfile(fpath):
fpath = locate_binary(fname)
if fpath is None:
if env.get('XONSH_DEBUG'):
print('source: {}: No such file'.format(fname), file=sys.stderr)
if i == 0:
raise RuntimeError('must source at least one file, ' + fname +
'does not exist.')
break
with open(fpath, 'r', encoding=encoding, errors=errors) as fp:
src = fp.read()
if not src.endswith('\n'):
src += '\n'
ctx = builtins.__xonsh_ctx__
updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)}
with env.swap(ARGS=args[i+1:]), swap_values(ctx, updates):
builtins.execx(src, 'exec', ctx, filename=fpath)
示例6: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source instead"""
for fname in args:
if not os.path.isfile(fname):
fname = locate_binary(fname, cwd=None)[:-1]
with open(fname, 'r') as fp:
execx(fp.read(), 'exec', builtins.__xonsh_ctx__)
示例7: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh_env__
encoding = env.get('XONSH_ENCODING')
errors = env.get('XONSH_ENCODING_ERRORS')
for fname in args:
if not os.path.isfile(fname):
fname = locate_binary(fname)
with open(fname, 'r', encoding=encoding, errors=errors) as fp:
builtins.execx(fp.read(), 'exec', builtins.__xonsh_ctx__)
示例8: sudo
def sudo(args, sdin=None):
if len(args) < 1:
print("You need to provide an executable to run as " "Administrator.")
return
cmd = args[0]
if locate_binary(cmd):
return winutils.sudo(cmd, args[1:])
elif cmd.lower() in windows_cmd_aliases:
args = ["/D", "/C", "CD", _get_cwd(), "&&"] + args
return winutils.sudo("cmd", args)
else:
msg = 'Cannot find the path for executable "{0}".'
print(msg.format(cmd))
示例9: sudo
def sudo(args, sdin=None):
if len(args) < 1:
print('You need to provide an executable to run as '
'Administrator.')
return
cmd = args[0]
if locate_binary(cmd):
return winutils.sudo(cmd, args[1:])
elif cmd.lower() in windows_cmd_aliases:
args = ['/D', '/C', 'CD', _get_cwd(), '&&'] + args
return winutils.sudo('cmd', args)
else:
msg = 'Cannot find the path for executable "{0}".'
print(msg.format(cmd))
示例10: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh_env__
encoding = env.get("XONSH_ENCODING")
errors = env.get("XONSH_ENCODING_ERRORS")
for fname in args:
if not os.path.isfile(fname):
fname = locate_binary(fname)
with open(fname, "r", encoding=encoding, errors=errors) as fp:
src = fp.read()
if not src.endswith("\n"):
src += "\n"
builtins.execx(src, "exec", builtins.__xonsh_ctx__)
示例11: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh__.env
encoding = env.get("XONSH_ENCODING")
errors = env.get("XONSH_ENCODING_ERRORS")
for i, fname in enumerate(args):
fpath = fname
if not os.path.isfile(fpath):
fpath = locate_binary(fname)
if fpath is None:
if env.get("XONSH_DEBUG"):
print("source: {}: No such file".format(fname), file=sys.stderr)
if i == 0:
raise RuntimeError(
"must source at least one file, " + fname + "does not exist."
)
break
_, fext = os.path.splitext(fpath)
if fext and fext != ".xsh" and fext != ".py":
raise RuntimeError(
"attempting to source non-xonsh file! If you are "
"trying to source a file in another language, "
"then please use the appropriate source command. "
"For example, source-bash script.sh"
)
with open(fpath, "r", encoding=encoding, errors=errors) as fp:
src = fp.read()
if not src.endswith("\n"):
src += "\n"
ctx = builtins.__xonsh__.ctx
updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)}
with env.swap(**make_args_env(args[i + 1 :])), swap_values(ctx, updates):
try:
builtins.execx(src, "exec", ctx, filename=fpath)
except Exception:
print_color(
"{RED}You may be attempting to source non-xonsh file! "
"{NO_COLOR}If you are trying to source a file in "
"another language, then please use the appropriate "
"source command. For example, {GREEN}source-bash "
"script.sh{NO_COLOR}",
file=sys.stderr,
)
raise
示例12: source_cmd
def source_cmd(args, stdin=None):
"""Simple cmd.exe-specific wrapper around source-foreign."""
args = list(args)
fpath = locate_binary(args[0])
args[0] = fpath if fpath else args[0]
if not os.path.isfile(args[0]):
return (None, 'xonsh: error: File not found: {}\n'.format(args[0]), 1)
prevcmd = 'call '
prevcmd += ' '.join([argvquote(arg, force=True) for arg in args])
prevcmd = escape_windows_cmd_string(prevcmd)
args.append('--prevcmd={}'.format(prevcmd))
args.insert(0, 'cmd')
args.append('--interactive=0')
args.append('--sourcer=call')
args.append('--envcmd=set')
args.append('--seterrpostcmd=if errorlevel 1 exit 1')
args.append('--use-tmpfile=1')
return source_foreign(args, stdin=stdin)
示例13: source_cmd
def source_cmd(args, stdin=None):
"""Simple cmd.exe-specific wrapper around source-foreign."""
args = list(args)
fpath = locate_binary(args[0])
args[0] = fpath if fpath else args[0]
if not os.path.isfile(args[0]):
return (None, "xonsh: error: File not found: {}\n".format(args[0]), 1)
prevcmd = "call "
prevcmd += " ".join([argvquote(arg, force=True) for arg in args])
prevcmd = escape_windows_cmd_string(prevcmd)
args.append("--prevcmd={}".format(prevcmd))
args.insert(0, "cmd")
args.append("--interactive=0")
args.append("--sourcer=call")
args.append("--envcmd=set")
args.append("--seterrpostcmd=if errorlevel 1 exit 1")
args.append("--use-tmpfile=1")
with builtins.__xonsh__.env.swap(PROMPT="$P$G"):
return source_foreign(args, stdin=stdin)
示例14: source_alias
def source_alias(args, stdin=None):
"""Executes the contents of the provided files in the current context.
If sourced file isn't found in cwd, search for file along $PATH to source
instead.
"""
env = builtins.__xonsh_env__
encoding = env.get('XONSH_ENCODING')
errors = env.get('XONSH_ENCODING_ERRORS')
for i, fname in enumerate(args):
fpath = fname
if not os.path.isfile(fpath):
fpath = locate_binary(fname)
if fpath is None:
if env.get('XONSH_DEBUG'):
print('source: {}: No such file'.format(fname), file=sys.stderr)
if i == 0:
raise RuntimeError('must source at least one file, ' + fname +
'does not exist.')
break
_, fext = os.path.splitext(fpath)
if fext and fext != '.xsh' and fext != '.py':
raise RuntimeError('attempting to source non-xonsh file! If you are '
'trying to source a file in another language, '
'then please use the appropriate source command. '
'For example, source-bash script.sh')
with open(fpath, 'r', encoding=encoding, errors=errors) as fp:
src = fp.read()
if not src.endswith('\n'):
src += '\n'
ctx = builtins.__xonsh_ctx__
updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)}
with env.swap(ARGS=args[i+1:]), swap_values(ctx, updates):
try:
builtins.execx(src, 'exec', ctx, filename=fpath)
except Exception:
print_color('{RED}You may be attempting to source non-xonsh file! '
'{NO_COLOR}If you are trying to source a file in '
'another language, then please use the appropriate '
'source command. For example, {GREEN}source-bash '
'script.sh{NO_COLOR}', file=sys.stderr)
raise
示例15: run_subproc
def run_subproc(cmds, captured=False):
"""Runs a subprocess, in its many forms. This takes a list of 'commands,'
which may be a list of command line arguments or a string, representing
a special connecting character. For example::
$ ls | grep wakka
is represented by the following cmds::
[['ls'], '|', ['grep', 'wakka']]
Lastly, the captured argument affects only the last real command.
"""
env = builtins.__xonsh_env__
background = False
procinfo = {}
if cmds[-1] == '&':
background = True
cmds = cmds[:-1]
_pipeline_group = None
write_target = None
last_cmd = len(cmds) - 1
procs = []
prev_proc = None
_capture_streams = captured in {'stdout', 'object'}
for ix, cmd in enumerate(cmds):
starttime = time.time()
procinfo['args'] = list(cmd)
stdin = None
stderr = None
if isinstance(cmd, str):
continue
streams = {}
while True:
if len(cmd) >= 3 and _is_redirect(cmd[-2]):
_redirect_io(streams, cmd[-2], cmd[-1])
cmd = cmd[:-2]
elif len(cmd) >= 2 and _is_redirect(cmd[-1]):
_redirect_io(streams, cmd[-1])
cmd = cmd[:-1]
elif len(cmd) >= 3 and cmd[0] == '<':
_redirect_io(streams, cmd[0], cmd[1])
cmd = cmd[2:]
else:
break
# set standard input
if 'stdin' in streams:
if prev_proc is not None:
raise XonshError('Multiple inputs for stdin')
stdin = streams['stdin'][-1]
procinfo['stdin_redirect'] = streams['stdin'][:-1]
elif prev_proc is not None:
stdin = prev_proc.stdout
# set standard output
_stdout_name = None
_stderr_name = None
if 'stdout' in streams:
if ix != last_cmd:
raise XonshError('Multiple redirects for stdout')
stdout = streams['stdout'][-1]
procinfo['stdout_redirect'] = streams['stdout'][:-1]
elif ix != last_cmd:
stdout = subprocess.PIPE
elif _capture_streams:
_nstdout = stdout = tempfile.NamedTemporaryFile(delete=False)
_stdout_name = stdout.name
elif builtins.__xonsh_stdout_uncaptured__ is not None:
stdout = builtins.__xonsh_stdout_uncaptured__
else:
stdout = None
# set standard error
if 'stderr' in streams:
stderr = streams['stderr'][-1]
procinfo['stderr_redirect'] = streams['stderr'][:-1]
elif captured == 'object' and ix == last_cmd:
_nstderr = stderr = tempfile.NamedTemporaryFile(delete=False)
_stderr_name = stderr.name
elif builtins.__xonsh_stderr_uncaptured__ is not None:
stderr = builtins.__xonsh_stderr_uncaptured__
uninew = (ix == last_cmd) and (not _capture_streams)
# find alias
if callable(cmd[0]):
alias = cmd[0]
else:
alias = builtins.aliases.get(cmd[0], None)
procinfo['alias'] = alias
# find binary location, if not callable
if alias is None:
binary_loc = locate_binary(cmd[0])
elif not callable(alias):
binary_loc = locate_binary(alias[0])
# implement AUTO_CD
if (alias is None and
builtins.__xonsh_env__.get('AUTO_CD') and
len(cmd) == 1 and
os.path.isdir(cmd[0]) and
binary_loc is None):
cmd.insert(0, 'cd')
alias = builtins.aliases.get('cd', None)
#.........这里部分代码省略.........