如何从需要在其自己的文件夹中运行另一个包的包中导入文件

问题描述 投票:0回答:1
revitalize/
├── app.py
├── static/
├── templates/
├── GFPGAN/
│   ├── experiments/
│   ├── gfpgan/
│   ├── inputs/
│   ├── results/
│   └── inference_gfpgan.py
└── DeOldify/
    ├── deoldify/
    ├── fastai/
    ├── fid/
    ├── test_images/
    ├── result_images/
    └── image_colorizer.py

这是文件夹树结构,在app.py中,我尝试从DeOldify导入image_colorizer,但是image_colorizer需要DeOldify包中的deolodify、fastai才能运行。因此这会导致在运行 Flask 应用程序时引发导入错误。

app.py

from flask import Flask, request, render_template, send_from_directory,redirect
from werkzeug.utils import secure_filename
import os

from DeOldify import imageColorizer


 
app = Flask(__name__)

reconstruct = True

loc1 = 'inputs\whole_imgs'
loc2 = 'DeOldify\\test_images'

upload = loc1 if reconstruct else loc2

app.config['UPLOAD'] = upload
 
@app.route('/', methods=['GET', 'POST'])
def file_upload():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD'], filename))
        return redirect('/reconstruct')
    return render_template('index.html')
 



@app.route('/colorize', methods=['GET','POST'])
def colorize():
    imageColorizer.ColorIMG()
    return render_template("index.html")

    

if __name__ == '__main__':
    app.run(debug=True, port=4339)

image_colorizer.py

from deoldify import device
from deoldify.device_id import DeviceId

from deoldify.visualize import *

def ColorIMG():
    # setting-up GPU
    device.set(device=DeviceId.GPU0)
.
.
.

我期待它使用 deoldify 中的

ColorIMG()
而不会出现任何导入错误。 我尝试从
deoldify
导入
app.py
但没有运气,我在网上查找了几个小时,但找不到此问题的任何相关解决方案。感谢您为解决此错误提供的任何帮助。预先感谢。

python file flask module importerror
1个回答
0
投票

要导入与另一个模块位于同一目录中的模块,您必须使用点符号进行相对导入。

from .deoldify import something
from .deoldify.some import thing

请注意,您无法在主脚本中进行相对导入,因为它作为顶层运行(您运行的用于启动的 Python 文件)。

# app.py
from .DeOldify import imageColorizer

它将生成一个

ImportError

image_colorizer.py
中你可以做类似的事情:

# image_colorizer.py
from ..GFPGAN import inference_gfpgan

但是在这种情况下它将不起作用,因为

GFPGAN
与app.py位于同一目录中,app.py作为顶级运行。并且点符号无法到达顶级/根目录。

注:
确保为将用作包和/或其中有要用作模块的 python 文件的每个目录创建一个

__init__.py
文件。

© www.soinside.com 2019 - 2024. All rights reserved.