在Python 3中将我的代码拆分为多个文件

时间:2016-03-14 23:18:58

标签: python python-3.x module packages

我希望将我的代码拆分为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'

3 个答案:

答案 0 :(得分:0)

换出

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!

答案 1 :(得分:0)

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

您应该在hello目录之外运行它并运行

python3
>>> import hello.first

顺便说一句,Python 3中不再需要__init__.py。请参阅PEP 420

答案 2 :(得分:0)

不打算从当前目录导入包。

可以使用if/else测试或try/except处理程序使其工作,但它的工作量超出了它的价值。

只需cd ..,这样您就不会进入软件包的目录,它可以正常运行。

相关问题