How to dynamically download files in one python directory

I am a beginner so any guidance is greatly appreciated I have a directory structure:

/testcases
 __init__.py, testcases_int/     
                  tc1.py,tc2.py,__init__.py,run.py

      

I intend to run each of these tc1.py, tc2.py .. tc (x) .py (x = new file will be added as needed) run.py I have code in run.py and tcx.py as:

#!/usr/bin/env python
import os,glob,subprocess
for name in glob.glob('tc*.py'):
  cmd = 'python name'
  subprocess.call(cmd)

      

#!/usr/bin/env python
import os,fabric,sys
class tc(object):
  def __init__(self):
     .....
  def step1(self):
     .....
  def step2(self):
     .....
  def runner(self):
     self.step1()
     self.step2()   

      

However, I do not intend to run it like above, instead I want to import the tc (x) .py classes into run.py and call the "runner" method for each tc (x) .py class

I could statically import each of the tc1.py, tc2.py files into run.py, but this directory will keep growing with the tc (x) .py files, so I want every time I run run.py: - it will dynamically load all tc (x) .py - create an instance of the tc (x) .py class - call the "runner" method

Thanks in advance

+3


source to share


3 answers


In main run mode, you can get all files from a directory How to list all files in a directory? And in the loop, use something like this:

for class_name in list_:
   import class_name
   runner_method = getattr(class_name, "runner", None) # if it staticmethod
   if callable(runner_method): 
      runner_method()

      



Or you can use __all__

in __init__.py

to useimport *

0


source


This is a great time to review modules unittest

and nose

to process testing. Both offer easy ways to automatically detect new tests based on (among other things) the filename. For example, all files starting with tc

or test_

.



0


source


I would recommend looking at the unittest (and similar) modules as paidhima said, but if you want to do it this way, the following is not particularly elegant, but works for my limited testing, assuming you can put the run script in the test table directory.

folder location

testcases/
|-- run.py
`-- tests
    |-- __init__.py
    |-- tc1.py
    `-- tc2.py

      

run.py
import tests
from tests import *

for tc in tests.__all__:
    getattr(tests,tc).tc().runner()

      

__init__.py
import glob, os
modules = glob.glob(os.path.dirname(__file__)+"/tc*.py")
__all__ = [ os.path.basename(f)[:-3] for f in modules ]

      

0


source







All Articles