簡體   English   中英

導入模塊在 Jupyter 筆記本和解釋器中的行為不同?

[英]importing module behaves differently in Jupyter notebook and Interpreter?

比如說,我們有一個模塊my_module.py

def test():
    pass

print("hello world")

另一個文件test.py有一行代碼

import my_module
  • 當我們運行python3 test.py時, Python 將打印出“hello world”
  • 在 Python 交互環境中,如果我們輸入“import my_module”,Python 也會打印出“hello world”

但是,在Jupyter notebook的一個單元格中,如果我寫了“import my_module”並運行該單元格,它不會打印出“hello world”消息……(盡管我可以調用 my_module.測試()函數)

這是 Jupyter 筆記本的預期行為嗎? 我很好奇為什么會有這樣的差異?

我猜您的問題是您在導入my_module時忽略了導入所有test.py (我假設你的__init__.py要么是空的,要么只是導入 function test() )。 如果您執行from my_module import testfrom my_module.test import * ,則一切都應按預期工作:

jupyter_img

請注意,我將test.py中的test()修改為:

def test():
    print("running test() in test.py")


編輯:我為混亂道歉,我不小心命名我的文件與你不同。 我最初沒有將任何文件命名為 my_module.py,而是讓 test.py 等同於您的 my_module.py。 我現在已經糾正了這一點。

我原來的文件夾結構如下:

def test():
    print("running test() in my_module.py")

print("goodbye world")

這是新的文件夾結構:

import my_module

my_module.test()

文件是

我的模塊.py

 def test(): print("running test() in my_module.py") print("goodbye world")

測試.py

 import my_module my_module.test()

如果你在Untitled.ipynbimport test ,你會得到以下信息: jupyter_img2

如果您關閉並重新連接 kernel,則可以import my_module以獲取以下內容: jupyter_img3

這按預期工作。

如果您希望它在my_module文件夾之外工作,我建議您重命名my_module.py 這是因為,在文件夾內,運行test.py會導入文件my_module.py ,而在文件夾外, test.py會導入整個文件夾my_module ,其中恰好包含test.py 要查看實際情況,請在import my_module之后將print(help(my_module))添加到test.py。 您會發現,根據您從哪里調用test.py ,這會打印出非常不同的內容。

為了提高清晰度,讓我們在文件夾中添加另一個名為test2.py的文件,並將my_module.py中的 function 從test()重命名為some_func()

從文件夾內部導入筆記本中的test.py會產生: jupyter_img4

從文件夾外部導入test.py會產生: jupyter_img5

如您所見,對於您希望test.py實際導入的內容有點困惑。

如果你想要第二個選項來打印隨機的東西,你可能不得不把它放在你的__init__.py文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM