在sphinx ipython指令中运行文件

问题描述

我是sphinx的新手,正在挣扎。

这是我的问题。我有一个文件usage.py,我想在我的文档中使用它。它包含纯python代码,就像这样(实际代码更长):

import matplotlib.pyplot as plt

# [start1]
import numpy as np
a = np.random.rand(5)
# [end1]

# [start2]
min(a)
# [end2]

def plot():
    plt.plot(a)

我希望能够像下面这样在我的usage.rst文件中使用该文件

Sample use
==========

In the first section,I just want to show some code:

.. literalinclude:: usage.py
   :language: python
   :start-after: [start1]
   :end-before: [end1]

In the second section,I want to plot something:

.. plot:: usage.py plot

   The array,graphically.

And in the third section,I want to actually show interpreter output:

.. ipython:: python

   run usage.py
   min(a)

问题出在第三部分:无法编译:

    run usage.py
            ^
SyntaxError: invalid Syntax

...即使在终端ipython界面上手动输入时,该行也可以正常工作。

我希望我的意图很明确:我希望所有代码都放在单独的.py文件中,以便于维护,并在不同的指令中使用它的不同部分。

理想情况下,我可以指示ipython将整个文件运行到特定的行号,并显示最终输入行的输出

感谢您的帮助。


编辑:部分解决方

这可以解决问题,并且没有错误

%run 'source/usage.py'
min(a)

但是,它不会显示正在运行的文件内容

在终端上手动使用%load时,根据需要用%run代替ipython 显示内容。但是,如果我对rst指令进行相同的更改,则代码甚至都不会执行。如果您对此有任何想法,请告诉我:)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)