如何将文件中的函数导入 jupyter notebook?

How to import a function from a file into a jupiter notebook?

我有一个 python 文件,来自 deep learning and go 上的这本书,如下所示。如果我执行 python.exe bot_v_bot.py,程序 运行s.

如果我从 eclipse/pydev 运行 bot_v_bot.py 就可以了。

.ipnb 文件与 bot_v_bot.py 在同一文件夹中。

如果我输入:

from bot_v_bot import main
main()

进入 .ipnb 文件中的一个单元格并 运行 它,它说:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-4-248b35949c67> in <module>()
----> 1 from bot_v_bot import main
      2 main()

ModuleNotFoundError: No module named 'bot_v_bot'

编辑:下面的代码有效。 eclipse 在 python 路径上有 src。

import sys
sys.path.append('src')
from bot_v_bot import main
main()

文件:bot_v_bot.py:

from __future__ import print_function
# tag::bot_vs_bot[]
from dlgo import agent
from dlgo import goboard_slow
from dlgo import gotypes
from dlgo.utils import print_board, print_move
import time


def main():
    board_size = 9
    game = goboard_slow.GameState.new_game(board_size)
    bots = {
        gotypes.Player.black: agent.naive.RandomBot(),
        gotypes.Player.white: agent.naive.RandomBot(),
    }
    while not game.is_over():
        time.sleep(0.3)  # <1>

        print(chr(27) + "[2J")  # <2>
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        game = game.apply_move(bot_move)


if __name__ == '__main__':
    main()

# <1> We set a sleep timer to 0.3 seconds so that bot moves aren't printed too fast to observe
# <2> Before each move we clear the screen. This way the board is always printed to the same position on the command line.
# end::bot_vs_bot[]

请检查并确保您的模块存在于任一系统路径下 (sys.path)

sys.path 值可以通过以下代码检索。

import sys
sys.path

如果sys.path中没有添加模块的路径,我们可以通过

追加sys.path中的路径
sys.path.append('C:\') # sample path C:\