Calling multiple Python files from one file

Hello,

Instead of having a long .py file with all my commands, how can I have my “MASTER.py” call different files (e.g., ‘densify.py’)?

I am referring to the equivalent of “Program call ‘densify.dat’” but for Python.

Is the syntax for calling another file the same if the file (‘densify.py’) contains user-defined functions or not? If so, what is the syntax?

Typical Python

Thanks!

This is a pure Python (rather than FLAC3D) question.

It’s a forum. I think all sort of questions may be asked… Perhaps my question should have been in “General” - tag : “Python”. My appologies if this is the case…

The “from densify import dens_coarse” command returns this error :

Python error: ModuleNotFoundError(“No module named ‘densify’”,)

I don’t have this issue when using Python in PyCharm, Spyder, etc. Seems like it only happens in FLAC3D.

1 Like

In “a.py”:
exec(open(“b.py”).read())

will call “b.py”

3 Likes

It works, thanks Zhao! I was also able to use this to pass along existing variables.

I know it’s an old question, but in case it could help.

My guess is that it’s only a matter of path environment variable: when importing a module in Python, it looks in the folder Python is executed from, and in its library folders (the defaults are %ProgramFiles%/Itasca/FLAC3D/exe64/python36/Lib and the site-packages subfolder in there).

If the module you’re trying to import is not in these, you’ll get an ImportError.
When executing from PyCharm, Spyder…, I guess the densify.py is in the folder you execute Python from. However, the execution folder of FLAC3D might not be this one (default is %ProgramFiles%/Itasca/FLAC3D/exe64).

If you wish to import a Python module from anywhere, you have to hardcode the path Python should look into in the script you’re executing (say MASTER.py) :

import sys
import pathlib

path_to_densify_headdir = pathlib.Path('path/to/folder/where/densify/is')
sys.path.append(str(path_to_densify_headdir))
import densify

Hope it helps.

1 Like