def process_sh_cmd(self, cmd):
"""{SH_EXEC} [cmd [args ...] | {{fmt string}}]
Escape to {SHELL} or execute `cmd` in {SHELL}
- without arguments, the current interpreter will be suspended
and you will be dropped in a {SHELL} prompt. Use fg to return.
- with arguments, the text will be executed in {SHELL} and the
output/error will be displayed. Additionally '_' will contain
a named tuple with the (<stdout>, <stderror>, <return_code>)
for the execution of the command.
You may pass strings from the global namespace to the command
line using the `.format()` syntax. for example:
>>> filename = '/does/not/exist'
>>> !ls {{filename}}
ls: cannot access /does/not/exist: No such file or directory
>>> _
CmdExec(out='', err='ls: cannot access /does/not/exist: No such file or directory\n', rc=2)
"""
if cmd:
try:
cmd = cmd.format(**self.locals)
cmd = shlex.split(cmd)
if cmd[0] == 'cd':
os.chdir(os.path.expanduser(os.path.expandvars(' '.join(cmd[1:]) or '${HOME}')))
else:
cmd_exec = namedtuple('CmdExec', ['out', 'err', 'rc'])
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
rc = process.returncode
print (red(err.decode('utf-8')) if err else green(out.decode('utf-8'), bold=False))
builtins._ = cmd_exec(out, err, rc)
del cmd_exec
except:
self.showtraceback()
else:
if os.getenv('SSH_CONNECTION'):
# I use the bash function similar to the one below in my
# .bashrc to directly open a python prompt on remote
# systems I log on to.
# function rpython { ssh -t $1 -- "python" }
# Unfortunately, suspending this ssh session, does not place me
# in a shell, so I need to create one:
os.system(config['SHELL'])
else:
os.kill(os.getpid(), signal.SIGSTOP)
评论列表
文章目录