Automate students tests run
<p>I have a folders structure for some tasks, they are like this:</p>

<pre><code>- student_id1/answers.py
- student_id2/answers.py
- student_id3/answers.py
- student_id4/answers.py
- ...
</code></pre>

<p>I have a main file: <code>run_tests.py</code>:</p>

<pre><code>from student_id1.answers import run_test as test1
from student_id2.answers import run_test as test2
...


try:
    test1()
    print("student_id1: OK")
except Exception as ee:
    print("Error for student_id1")

try:
    test2()
    print("student_id2: OK")
except Exception as ee:
    print("Error for student_id2")
...
</code></pre>

<p>There can be more folders as they are adding with each new student. I would like to call all tests with a single command, but do not want to add so much lines with each new student.</p>

<p>How can I automate this?</p>

<p>You can use <code>importlib</code> module: <a href="https://docs.python.org/3/library/importlib.html" rel="nofollow">https://docs.python.org/3/library/importlib.html</a></p>

<pre><code>import os
import importlib

for student_dir in os.listdir():
    if os.path.isdir(student_dir):
        # here you may add an additional check for not desired folders like 'lib', 'settings', etc
        if not os.path.exists(os.path.join(student_dir, 'answers.py')):
            print("Error: file answers.py is not found in %s" % (student_dir))
            continue
        student_module = importlib.import_module("%s.answers" % student_dir)
        try:
            student_module.run_test()
            print("%s: OK" % student_dir)
        except Exception as ee:
            print("Error for %s" % student_dir)
</code></pre>

python