Borja
Borja

Reputation: 3559

How use variable defined in one module in another module?

I want to pass a variable from fileA.py to fileB.py but i don't know how use (import) it in fileB.py.

I have this situation (frames folder and file.A are at same level)

frames
  |
  folder
    |
    fileB.py

fileA.py

In the fileA.pyi have an image and i want to pass it in fileB.py

immagine= cv2.imread('image.jpg')
os.chdir("frames/folder")
subprocess.call(["python", "fileB.py", 'immagine'])

I think this works well but i don't know how import immagine in fileB.py. Maybe i should to use:

from ..fileA.py from immagine

but not works and i have this error: ImportError: attempted relative import with no known parent package

I hope you can help me... i'm really new in python (like Ide i use pycharm and i use it to install modules - of course fileB.py and fileA.py aren't modules but normal python files)

Upvotes: 0

Views: 315

Answers (2)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15575

Your requirements are unclear, so I'll just question all of them. You should not use a subprocess and you should not use shared memory, or any other hack.

You should simply define a function in fileB.py:

# frames/folder/fileB.py

def do_something(im):
    # do something to im
    # return something
    return im.shape # for example

if __name__ == '__main__':
    # when running this script directly, do whatever you need to here
    # e.g. use a command line argument, read as an image file, call your function...
    ...

and then, in fileA.py, you do this:

# fileA.py

from frames.folder.fileB import do_something
res = do_something(image)
print(res)

And that's all!

If you need the opposite, i.e. in the inner file, you want to call functions defined in the outer file, then you do need to make this a package, so you can use a relative import.

Upvotes: 0

mikelsr
mikelsr

Reputation: 457

I can think of two solutions, one using your subprocess call and another one with import:

Easiest solution

You can treat them as console command parameters and read them with sys.argv.

For example in fileB.py:

from sys import argv
var = argv[1]

print(var)

Should output: immagine

Arguably best solution

Another way of doing it is to make both fileA.py and fileB.py part of the same module, even if fileB.py is a different submodule. For example:

mymodule
|    |  |
|    | fileA.py
|    |
|   folder
|      |
|     fileB.py
|  
__init__.py (this marks mymodule as a moduke)

And then in fileB.py:

from mymodule.fileA import immagine

Take into account that you must run fileA with python -m mymodule.fileA for this to work.

Upvotes: 1

Related Questions