Cirrith
Cirrith

Reputation: 196

Import and run all modules in folder

Is there a way to import and run all .py files in a folder?

Basically how I think pytest does its test discovery.

It seems like I would want to import from a file path into a list and then iterate through the list calling .main(*args) on each module.

It also needs be python 2 and 3 compatible

Example

Upvotes: 3

Views: 1483

Answers (1)

amitchone
amitchone

Reputation: 1638

You can use importlib. Assume the following simple directory structure:

  • a.py
  • b.py
  • c.py

a.py and b.py contain the following simple function:

def main(name):
    print name

In c.py we can iterate over our directory and use importlib.import_module to import each file. We must ensure to make the imported modules globally accessible, otherwise they will only be local to the for loop.

c.py:

import importlib

files = ['a', 'b']

for f in files:
    globals()[f] = importlib.import_module(f)

a.main('adam')
b.main('ben') 

Running c.py produces the following output:

adam
ben

Upvotes: 4

Related Questions