【问题标题】:Could we run ipython commands in python?我们可以在 python 中运行 ipython 命令吗?
【发布时间】:2021-06-16 07:13:55
【问题描述】:

假设我想使用 jupiter notebook/ipython 作为开发环境,然后将所有内容复制到 python 脚本中。在 ipython 中,我们有类似

的命令
In [1]: cd ..
/Users/myname/Desktop/software

In [2]: ls
  blah_blah_blah/ 

假设我完成了我的 ipython 笔记本并想要复制所有内容(假设我有 1000 行并且我无法逐个编辑它们)来创建我的 python 脚本。是否可以让我的 python 脚本理解诸如“cd ..”之类的行。

【问题讨论】:

  • osos.path模块可以做cd之类的事情。

标签: python ipython


【解决方案1】:

使用标准 Python 解释器运行IPython 代码的任何方法都会有点复杂。例如,请参阅this 问题,其中一个答案说明了调用 IPython 的“魔术”方法来执行 shell 命令:

from IPython.terminal.embed import InteractiveShellEmbed

ipshell = InteractiveShellEmbed()
ipshell.dummy_mode = True
ipshell.magic("%timeit abs(-42)")

更简单的选择是简单地使用 IPython 解释器来运行您保存的脚本。您需要确保每个 shell 命令前面都有一个%,因为这表示一个“魔术”命令。应该是一个简单的查找和替换任务,因为我怀疑你使用了太多的 shell 命令。如果有很多不同的 shell 命令以 % 为前缀,您还可以编写一个简短的脚本来为您完成这项工作。您还需要确保您的脚本具有扩展名.ipy

script.ipy:

%cd ..
%ls
x = "My script!"
print(x)

从终端运行脚本:

>>> ipython script.ipy

【讨论】: