【问题标题】:How to import python file in another Flask? [duplicate]如何在另一个 Flask 中导入 python 文件? [复制]
【发布时间】:2018-05-15 00:41:49
【问题描述】:

我有一个init.py 文件。我在同一路径中有一个子目录/controller

我尝试像这样在init.py 中导入文件/controller/file.py

import controller/file
import controller/file.py

它不起作用。如何在 Flask 框架中轻松做到这一点,或者在 Python 中默认做到这一点?

【问题讨论】:

标签: python python-2.7 flask


【解决方案1】:

首先,您必须放在那里的文件称为__init__.py。其次,你通常应该把这些留空,除非你想要一些非常具体的行为。

最后,看看这个文件夹结构

- __init__.py
- main.py
+ foo
  - __init__.py
  - foo_app.py
+ bar
  - __init__.py
  - bar_app.py

foo_app.py

import bar.bar_app

编辑:为此,必须从父目录启动应用程序。

【讨论】:

  • 当我尝试这个时,我得到:ImportError: No module named controller.file
  • 我用这个:import flask.controller.api
【解决方案2】:

正如上面 cmets 中提到的@Davidism,您将导入文件“与在其他任何地方导入的方式相同。导入路径由点分隔,而不是斜线。”

假设你有这样的文件结构

/Project
 --program.py
   /SubDirectory
    --TestModule.py

在这个例子中,假设TestModule.py 的内容是:

def printfunction(x):
    print(x)

现在让我们先开始吧,在你的program.py 中你需要import sys 然后使用这行代码将你的子目录添加到python的环境路径中

import sys
sys.path.insert(0, os.getcwd()+"/SubDirectory")

现在您可以正常导入模块了。继续上面描述的文件结构,您现在可以像这样导入模块

import TestModule 

您现在可以像往常一样从TestModule.py 文件中调用函数printfunction()

TestModule.printfunction("This is a test! That was successful!");

这应该输出:

This is a test! That was successful!

您的program.py 文件应如下所示:

import sys
sys.path.insert(0, os.getcwd()+"/SubDirectory")    
import TestModule
TestModule.printfunction("This is a test! That was successful!");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 2020-08-18
    • 1970-01-01
    • 2014-05-22
    • 2020-04-28
    • 2018-02-28
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多