2

I'm trying to validate multiple functions from separate files all with the same names.

So, consider I have a directory of directories: dir1 which has s1,s2,s3,...,sn which all are directories and each contain a file called submission.py. I do not know what s1 through sn are until run time.

In each submission.py, there's functions f1 through fm.

I would like to create a script that executes f1 through fm and prints their output for each s1 through sn's submission.py file.

I would like to think that I could import each submission.py file in each directory, but the problem is that each file has the same name. Also, s1 through sn is not known until run time. Obviously, I can determine s1 through sn using the os.listdir function.

Any idea on how I can call f1 from two different files after getting the names of the directories through os.listdir?

2
  • Do the subdirectories s1,s2,s3 etc each contain __init__.py files? Commented Apr 13, 2016 at 16:54
  • No. The subdirectories are actually intro student submission directories and they're just submitting simple scripts. Commented Apr 13, 2016 at 17:12

1 Answer 1

2

This is possible using imp.

>>> import os, imp
>>> dirs = os.listdir('.')
>>> dirs
['s1', 's2']
>>> modules = {d: imp.load_source(d, d + '/submission.py') for d in dirs}
>>> modules
{'s1': <module 's1' from 's1/submission.py'>,
 's2': <module 's2' from 's2/submission.py'>}

Then, to call a function f3 in the submission.py module contained in subdirectory s2 for example, it would be:

modules['s2'].f3()
Sign up to request clarification or add additional context in comments.

1 Comment

This solution is beautiful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.