'How can I loop through a dir of python scripts, calling specific functions? [duplicate]

I am trying to figure out if it is possible to loop over a directory of python scripts and call a specific function I know will be there.

If I have a structure like this

.
└── app dir/
    ├── app.py
    └── scripts/
        ├── foo.py
        ├── bar.py
        ├── 123.py
        └── ...

And I know that each file in scripts has a function called getName(), is it possible to loop over them and call that function inside app.py?

At the moment I use a subprocess in app.py to call the scripts and use sys.argv inside the scripts to print the output of functions... I'd rather just call the functions directly if possible.

If it is possible, would I be able to have the scripts directory be "dynamic" where all scripts are imported automatically?



Solution 1:[1]

Yup, it is. When I understood it correctly, you can loop over them, when you have all files in one directory (and it would be better to call the functions like Name1(), Name2(). When you've done that, than just import the functions from the different py3 files. Like:

from scripts import Name1
from bar import Name2
...

That's the most simple way to do it ;D

Solution 2:[2]

Why to import them through a loop, when you can directly import them?

One of your probable reason could be because they all contain a function with same name, well you can solve it using:

from app.script.foo import getName as gn1
from app.script.bar import getName as gn2

# Then to call them use
gn1() 
gn2()

as keyword will import the file and you would be able to call them using the keyword you have specified while importing like in above example I have used import getName as gn1, so now I can access that particular function using gn1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rylixmods
Solution 2 Faraaz Kurawle