从 IPython 执行 Bash 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15927142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:34:26  来源:igfitidea点击:

execute Bash command from IPython

bashipython

提问by chris

I want to source my bash environment when executing a bash command from IPython using the !operator, thus allowing me access to my defined bash functions:

我想在使用!操作符从 IPython 执行 bash 命令时获取我的 bash 环境,从而允许我访问我定义的 bash 函数:

In[2]: !<my_fancy_bash_function> <function_argument>

currently IPython is sourcing shrather than bash:

目前 IPython 正在采购sh而不是bash

In[3]: !declare -F
sh: 1: declare: not found

How to source bashand set my environment settings from IPython?

如何bash从 IPython 获取和设置我的环境设置?

回答by Jason Sundram

Fernando Perez, creator of IPython, suggests this:

IPython 的创建者 Fernando Perez建议

In [1]: %%bash
. ~/.bashrc
<my_fancy_bash_function> <function_argument>

This works on the current stable version (0.13.2). He admits that's a bit clunky, and welcomes pull requests. . .

这适用于当前的稳定版本 (0.13.2)。他承认这有点笨拙,并欢迎拉取请求。. .

回答by D.Shawley

If the !implementation uses IPython.utils._process_posix.systemunder the hood, then it is going to use whatever which shreturns as the processing shell. This could be a true implementation of Bourne shell - it is likely Bash in some compatibility mode on many Linuxes. On my MacBook Pro it looks like it is a raw Bash shell:

如果!实现IPython.utils._process_posix.system在幕后使用,那么它将使用任何which sh返回作为处理外壳。这可能是 Bourne shell 的真正实现——它可能在许多 Linux 上以某种兼容模式使用 Bash。在我的 MacBook Pro 上,它看起来像是一个原始的 Bash shell:

In [12]: !declare -F

In [13]: !echo $BASH
/bin/sh

In [14]: !echo $BASH_VERSION
3.2.48(1)-release

In [15]: import os

In [16]: os.environ['SHELL']
Out[16]: '/bin/zsh'

I was hoping that it would use the $SHELLenvironment variable but it does not seem to today. You can probably branch the github repo, modify the ProcessHandler.shproperty implementation to peek into os.environ['SHELL']and use this if it is set instead of calling pexpect.which('sh'). Then issue a pull request.

我希望它会使用$SHELL环境变量,但今天似乎没有。您可能可以分支 github 存储库,修改ProcessHandler.sh属性实现以查看os.environ['SHELL']并使用它,如果它被设置而不是调用pexpect.which('sh'). 然后发出拉取请求。