【问题标题】:Interacting with IPython kernel from a Bash script从 Bash 脚本与 IPython 内核交互
【发布时间】:2014-06-10 15:35:54
【问题描述】:

是否可以通过 Bash 脚本与 IPython 交互式会话(或内核)进行交互?理想情况下,我想在 shell 脚本中做这样的事情(我知道 send 子命令可能不存在这样的):

# do stuff in Bash ...
# start a kernel and get its Id
KERNEL=`ipython init --command="print(__KERNELID__)"`
# do something inside the kernel
ipython send --kernel=KERNELID --command="mylist = [0,1,2]"

然后,理想情况下,命令

ipython send --kernel=KERNELID --command="print(mylist)"

会输出

[0, 1, 2]

最后,我需要以某种方式破坏内核:

ipython --kernel=KERNELID --command="sys.exit()"

可能已经有一种机制可以做我想做的事, 正确的?不幸的是,我没能找到它...

【问题讨论】:

    标签: ipython


    【解决方案1】:

    有很多方法可以解决这个问题。由于您必须使用 python,因此您不妨将 python 用于整个事情。 Python 程序可以使用 mylist 之类的命令行参数,然后对它们做任何你想做的事情。

    由于您要发送要评估的命令,请确保您是控制输入的人。例如,不要让某人开始输入“import os”和“os.unlink([your hard drive here])”。

    对于其他选项:查看期待您的交互需求http://expect.sourceforge.net/ 或者只是 python 版本查看 pexpect 模块http://pexpect.sourceforge.net/pexpect.html

    【讨论】:

    • 感谢您的回答!事情是在 Bash 脚本的过程中,我需要一遍又一遍地访问同一个 Python 会话。这意味着,在 bash 脚本中的某一时刻,我需要将一些信息提供给 Python 会话,而在稍后阶段,我需要从该 Python 会话中检索信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2015-01-20
    相关资源
    最近更新 更多