![](/img/trans.png)
[英]how to import a python file which is further importing other files. without getting ImportError?
[英]Python: Importing own files. Why does “import myFile” not work?
為了構建我的python項目,我想到了將代碼分成不同的文件。
我在此處找到了有關導入的大量指南,示例1似乎很適合我的需求。
因此,我使用以下代碼創建文件part.py
:
print("Hello world")
def myFunction():
print("This is my function!")
然后我在同一文件夾中創建了destination.py
:
import part
# from part import *
myFunction()
正如我期望的那樣, import part
將運行part.py的整個代碼,我的最終結果是
Hello world
This is my function!
但是,我得到了
ModuleNotFoundError Traceback (most recent call last)
in ()
----> 1 import part
2 # from part import *
3
4 myFunction()
ModuleNotFoundError: No module named 'part'
使用# from part import *
代替import part
會導致相同的錯誤。
我究竟做錯了什么?
編輯:@hiro主角:我將一個空的__init__.py
文件放入同一詞典中。 重新啟動內核后,運行destination.py中的所有代碼時,我會(注意hello world
):
Hello world
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
2 # from part import *
3
----> 4 myFunction()
NameError: name 'myFunction' is not defined
再次運行destination.py中的所有代碼后,我只得到
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
2 # from part import *
3
----> 4 myFunction()
NameError: name 'myFunction' is not defined
如果現在執行第三part.py
,請運行part.py
所有代碼,我得到
Hello world
然后,我可以運行destination.py
所有代碼來獲取
This is my function!
如果我只能以相同的結果一次又一次地運行destination.py
,我會更喜歡。
@Nullman: part.py
是文件,但是import .part
拋出
File "", line 1
import .part
^
SyntaxError: invalid syntax
@Jeyekomon:我正在Windows 10和Python 3.7.0上使用Visual Studio Code。
@ 9769953:我直接在Visual Studio Code中運行代碼
該模塊導入問題似乎現在已解決。 盡管在Python 3中通常不再需要 __init__.py
文件,但是您正在使用的Visual Studio Code似乎仍然需要它。
其余的問題與使用模塊有關。 從官方Python教程中學習創建和使用模塊的基礎知識。 模塊part
應包含可在主文件destination
調用的函數:
destination.py :
import part
part.say_hello()
part.myFunction()
part.say_hello()
part.py :
def say_hello():
print("Hello world")
def myFunction():
print("This is my function!")
將您的destination.py更改為:
from part import *
myFunction()
這對我行得通
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.