我们可以在 python 中运行 ipython 命令吗?

use*_*780 6 python ipython

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

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

In [2]: ls
  blah_blah_blah/ 
Run Code Online (Sandbox Code Playgroud)

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

And*_*Guy 4

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

from IPython.terminal.embed import InteractiveShellEmbed

ipshell = InteractiveShellEmbed()
ipshell.dummy_mode = True
ipshell.magic("%timeit abs(-42)")
Run Code Online (Sandbox Code Playgroud)

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

脚本.ipy:

%cd ..
%ls
x = "My script!"
print(x)
Run Code Online (Sandbox Code Playgroud)

要从终端运行脚本:

>>> ipython script.ipy
Run Code Online (Sandbox Code Playgroud)