0

I am scanning a directory for new python scripts. I expect each script file to have an arbitrary function report(). Say, the following files were found in my directory: ['file1.py', 'file2.py']. So "file1.py" should contain:

def report():
    print('I am just a script.')

I need to call report() function for each one of them. How to do it?

minerals
  • 6,090
  • 17
  • 62
  • 107
  • Your question is not clear. What have you tried so far? Post any code samples along with the specific issue you are having. – Greg Nov 16 '15 at 23:27

1 Answers1

1

You can use the builtin function __import__ to do a dynamic import, something like this:

for file in files:
    mod = __import__(file)
    mod.report()

Note - you will need to strip the '.py' extension from the filename, and this will be made more complicated if the current working directory is not on the python path.

This SO answer has some more detail on __import__(): Dynamic module import in Python. If you need to load from somewhere off the python path, then look at the second answer

Community
  • 1
  • 1
Harry Harrison
  • 591
  • 4
  • 12