如上所述,我们可以使用命令行中的ipython来运行ipython脚本:
ipython my_script.ipy
然而,魔法单元格目前效果不佳。例如,如果您有以下脚本:
%%writefile hello.txt
this is a line
another line
print ('hello')
my_path = '/path/to/folder'
list_of_txt = !ls {my_path}/*.txt
print (list_of_txt)
它将运行初始单元格魔术命令%%writefile
,就好像整个文件是一个单独的单元格。为了避免这种情况,您必须使用get_ipython().run_cell_magic()
由于每个IPython命令都需要不同的函数,我发现编写您想要在笔记本中使用的IPython命令,然后在笔记本的菜单中执行文件>"保存和导出笔记本为">"可执行脚本"
(在jupyter lab中,但可能可以在普通的jupyter notebook中进行类似的操作)。它将使用IPython库中的适当函数转换所有特定于IPython的代码。
例如,如果我们将先前的脚本复制并粘贴到笔记本的不同单元格中,并将其导出为.py文件,则会给我们生成以下Python代码:
导出脚本中编写的代码:
get_ipython().run_cell_magic('writefile', 'hello.txt', 'this is a line\nanother line\n')
my_path = '/path/to/folder'
list_of_txt = get_ipython().getoutput('ls {my_path}/*.txt')
print (list_of_txt)
您可以直接使用命令行中的ipython运行导出的脚本:
ipython my_exported_script.py
或者,在ipython
会话中,使用以下命令:
%run my_exported_script.py
这适用于 IPython 1.x 版本
os
和os.path
模块可以执行像cd
这样的操作。 - hpaulj