分割我的代码分割成多个文件在Python 3

问题描述:

我希望我的代码分割成多个文件在Python 3分割我的代码分割成多个文件在Python 3

我有以下文件:

/hello 
    __init__.py 
    first.py 
    second.py 

当上述文件的内容:

first.py

from hello.second import say_hello 

say_hello() 

second.py

def say_hello(): 
    print("Hello World!") 

但是当我运行:

python3 first.py 

而在hello目录我得到以下错误:

Traceback (most recent call last): 
    File "first.py", line 1, in <module> 
    from hello.second import say_hello 
ImportError: No module named 'hello' 
+2

你真的*安装了*你的包吗?将它添加到路径中?考虑一个相对导入('from .second import say_hello')而不是? – jonrsharpe

+0

我没想到你需要。我只是想将我的代码拆分为多个文件,就像几乎所有语言(如Java或PHP)一样。 –

+1

然后我建议你停止猜测并阅读例如https://docs.python.org/3/tutorial/modules.html – jonrsharpe

换出

from hello.second import say_hello 

from second import say_hello 

你默认的Python路径将包括当前目录,所以从second进口直会工作。您甚至不需要此文件__init__.py。您,但是,需要__init__.py文件,如果你想从包装的外面导入:

$ python3 
>>> from hello.second import say_hello 
>>> # Works ok! 
+2

'__init __。py'在Python 3中不再需要。参见[PEP 420](https://www.python.org/dev/peps/pep-0420 /) – Bharel

+0

当你在package目录之外时,你的建议会导致'import hello.first'问题。 –

你不应该运行在hello目录python3。

你应该hello目录外运行并运行

python3 
>>> import hello.first 

顺便说一句,不再需要在Python 3见PEP 420__init__.py

+0

这给我的错误:'回溯(最近通话最后一个): 文件 “你好/ first.py”,1号线,在 从hello.second进口say_hello 导入错误:没有名为“模块hello'' –

+0

@ YahyaUddin:这个答案有效,你一定做错了。 –

包并不意味着从当前目录导入。

可以使用if/else测试或try/except处理程序使其工作,但它的工作量比它值得的更多。

只是cd ..所以你不在包的目录中,它会正常工作。