How to use functions that are in a different file? - Python

Asked

Viewed 1,772 times

0

I’m having a problem using functions that are in a different file than where I’m calling these functions. Basically my project is organized as follows:

Lista_I (Pacote Contendo os Arquivos)
    __init__.py
    funcoes_uteis.py
    PDI.py

In the archive PDI.py I have the following code:

import numpy

def aplicar_mascara_media_aritmetica(imagem):

    filtro = numpy.zeros((3, 3))

    for i in range(1, len(imagem) - 1):
        for j in range(1, len(imagem[0]) - 1):
            filtro[0][0] = imagem[i - 1][j - 1]
            filtro[0][1] = imagem[i - 1][j]
            filtro[0][2] = imagem[i - 1][j + 1]
            filtro[1][0] = imagem[i][j - 1]
            filtro[1][1] = imagem[i][j]
            filtro[1][2] = imagem[i][j + 1]
            filtro[2][0] = imagem[i + 1][j - 1]
            filtro[2][1] = imagem[i + 1][j]
            filtro[2][2] = imagem[i + 1][j + 1]

            imagem[i][j] = calcular_media(filtro) #não funciona

    return imagem

And in the archive funcoes_uteis.py i have the function calcular_media(filtro) that is being called into the archive PDI.py. I’ve tried to do import funcoes_uteis but it’s not working. I don’t know if this has anything to do with the python version I’m using, but just in case, I’m using python version 3.6. Can anyone help me with this problem? Thank you in advance!

1 answer

1


In the PDI.py add:

import funcoes_uteis

And call:

imagem[i][j] = funcoes_uteis.calcular_media(filtro)

Or if you don’t want to use it as funcoes_uteis.calcular_media call it that:

from funcoes_uteis import calcular_media

And call:

imagem[i][j] = calcular_media(filtro)

I created two very simple test scripts

PDI.py

import funcoes_uteis

def aplicar_mascara_media_aritmetica():
    return funcoes_uteis.calcular_media(2)

print(aplicar_mascara_media_aritmetica())

funcoes_uteis.py

def calcular_media(imagem):
    return imagem

And then I executed in cmd:

exemplo

  • I tried to do both but none of them worked

  • @Cloudac did not work is very ambiguous and tells me nothing about it so that I understand where the fault went, what error it gave on the screen?

  • "No module named funcoes_uteis". It’s like he hasn’t seen the file.

  • @Cloudac edited the answer, see the example part and the test I did on my computer, you probably got mixed up in something.

  • @Cloudac Who runs your python script? It’s Django/Flask or is using with wsgi and Apache?

  • so, I installed python from Anaconda 4.4.0 and was running scripts with Pycharm IDE. But I tried now to run the script directly by windows cmd and got the same problem

  • 1

    I uninstalled everything about python I had on my machine and reinstalled it. Now you’re working normal the way you taught, thank you for answering and for your patience!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.