Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从其他.py文件导入类时,Flask不工作_Python_Python Import - Fatal编程技术网

Python 从其他.py文件导入类时,Flask不工作

Python 从其他.py文件导入类时,Flask不工作,python,python-import,Python,Python Import,我正在使用Flask创建一个web应用程序,并试图从与app.py文件位于同一目录下的.py文件中导入另一个类,但导入不起作用 详细说明: 这是我的代码,运行良好 from flask import Flask import os from flask import Flask, request, render_template, redirect, url_for, flash from flask import send_from_directory #from moleimages im

我正在使用Flask创建一个web应用程序,并试图从与app.py文件位于同一目录下的.py文件中导入另一个类,但导入不起作用

详细说明:

这是我的代码,运行良好

from flask import Flask
import os

from flask import Flask, request, render_template, redirect, url_for, flash
from flask import send_from_directory
#from moleimages import MoleImages
import random
from werkzeug.utils import secure_filename
from keras.models import load_model
import tensorflow as tf
from keras.models import model_from_json

app = Flask(__name__)

@app.route('/')
def index():
    return 'hi'

if __name__ == "__main__":
    app.run(debug=True)
现在,第二次我取消注释“from moleimages import moleimages”,命令提示符不会为flask应用程序生成任何输出,它将终止

终端图像:

工作罚款:

现在,当我取消对moleimages导入的注释时:

烧瓶应用程序只是自动终止

有人知道为什么会这样吗?moleimages文件本身工作正常,不会产生错误。这是moleimages文件

'''
Author@PranavEranki
'''
import numpy as np
from skimage import io
from skimage.transform import resize
import glob
import h5py
import os


'''
This is the helper method for image prep
'''
class MoleImages():
    def __init__(self, dir=None):
        self.dir = dir
        self.size = None

    # Resizing multiple images to a 128 x 128 size
    def resize_bulk(self, wtype, size=(128,128)):
        '''
        Resize Images and create matrix
        Input: size of the images (128,128)
        Output: Numpy array of (size,num_images)
        '''
        self.size = size
        X = []
        image_list = glob.glob(self.dir) #Getting images we need to resize
        n_images = len(image_list)
        most = 2000
        if n_images > most:
            n_images = most
            image_list = image_list[:n_images]
        # Resizing of the images with verbosity
        print('Resizing {} images:'.format(n_images))
        for i, imgfile in enumerate(image_list):
            print('Resizing image {} of {}'.format(i+1, n_images))
            img = io.imread(imgfile)
            img = resize(img, self.size)

            X.append(img)


        return np.array(X)

    def load_test_images(self, dir_b, dir_m):
        X = []
        image_list_b = glob.glob(os.path.join(os.getcwd(), dir_b + '/*.png'))

        n_images_b = len(image_list_b)
        print('Loading {} images of class benign:'.format(n_images_b))
        for i, imgfile in enumerate(image_list_b):
            print('Loading image {} of {}'.format(i+1, n_images_b))
            img = io.imread(imgfile)
            X.append(img)
        image_list_m = glob.glob(os.path.join(os.getcwd(), dir_m + '/*.png'))

        n_images_m = len(image_list_m)
        print('Loading {} images of class benign:'.format(n_images_m))
        for i, imgfile in enumerate(image_list_m):
            print('Loading image {} of {}'.format(i+1, n_images_m))
            img = io.imread(imgfile)
            X.append(img)

        y = np.hstack((np.zeros(n_images_b), np.ones(n_images_m)))

        return np.array(X), y.reshape(len(y),1)

    def load_image(self, filename, size=(128,128)):
        self.size = size
        img = io.imread(filename) #Getting image
        img = resize(img, self.size, mode='constant') * 255 # Resizing image
        if img.shape[2] == 4: #Making sure everything is 3 channels only
            img = img[:,:,0:3]
        return img.reshape(1, self.size[0], self.size[1], 3)

    def save_h5(self, X, filename, dataset):
        '''
        Save a numpy array to a data.h5 file specified.
        Input:
        X: Numpy array to save
        filename: name of h5 file
        dataset: label for the dataset
        '''
        with h5py.File(filename, 'w') as hf:
            hf.create_dataset(dataset, data=X)
        print('File {} saved'.format(filename))

    def load_h5(self, filename, dataset):
        '''
        Load a data.h5 file specified.
        Input: filename, dataset
        Output: Data
        '''
        with h5py.File(filename, 'r') as hf:
            return hf[dataset][:]

    def save_png(self, matrix, dir, tag='img', format='png'):

        # Saving the picture to the directory
        for i, img in enumerate(matrix):
            current_dir = os.getcwd()
            # getting the appropriate filename and directory
            if dir[-1] != '/':
                current_dir = (os.path.join(current_dir, dir + "/"))
                filename = tag + str(i) + '.' + format
            else:
                current_dir = (os.path.join(current_dir, dir))
                filename = tag + str(i) + '.' + format

            # this is some verbosity which I implemented for bug testing - not important
            print('Saving file {}'.format(filename))
            print(current_dir)

            # Making rhe dir benign / malign for data scaled if not present
            if not os.path.exists(current_dir):
                os.makedirs(current_dir)

            # Saving the image to the proper directory
            current_dir = os.path.join(current_dir, filename)

            io.imsave(current_dir, img)



if __name__ == '__main__':
    pass
    #benign = MoleImages()
    #X = benign.load_h5('benigns.h5','benign')

如果
moleimages.py
位于同一目录中,您可能需要将导入更改为
from.moleimages导入moleimages

通过这种方式,您可以告诉python从同一文件夹加载具有该名称的文件。否则,python将寻找名为
moleimages
的模块

另一种方法是使用绝对导入,但我无法告诉您在不了解应用程序层次结构的情况下会是什么样子

您可以在中阅读有关相对导入和绝对导入的更多信息


编辑:还要确保目录中有
\uuuu init\uuuu.py
您是否尝试导入
.moleimages
?您还可以创建一个名为
PYTHONPATH
的env变量,并设置您的工作目录。这个env变量可以从python中读取。

当我使用from.moleimages导入moleimages时,我得到一个错误-尝试在没有已知父包的情况下进行相对导入。你知道为什么会发生这种情况吗?文件夹中是否有
\uuuu init\uuuu.py
文件?没有。没有.py文件会干扰任何函数,因为它们都有唯一的名称。唯一可能出现问题的文件是app.py,这是我的Flask文件。您需要在每个要从中导入的文件夹中都有一个
\uuu init\uuu.py
。一般来说,在有py文件的每个目录中都有一个py文件是一种很好的做法。你可以在这里读更多,我试过这个,但它没有改变任何事情。我创建了一个
\uuuu init\uuuu.py
文件,并将其留空。这就是我应该做的,是吗?