简体   繁体   中英

Dynamically Call Different Python Files with dynamically importing

I have a folder structure like

Current Folder > DC > F > 

Current contains a A.py file which I will execute, which is my main py file.

F Folder will have numerous *.py files which all have a class and its constructor

DC Folder will have few *.py files which the *.py files in F is using

I am importing a xml file which I am reading from the main A.py file, which is of the following format.

<Test>DC\F\TestCase1</Test>
<Test>DC\F\TestCase2</Test>

I have my main A.py which does this

if (line.startswith("<Test>")):
      result = re.search('<Test>(.*)</Test>', line)
      filename = result.group(1).split('\\')[-1]
      eval(filename)(self.getWebDriver())

and it works fine. But the problem is, it is expecting this

from DC.F.TestCase1 import TestCase1
from DC.F.TestCase2 import TestCase2

How do I get rid of this import statements, so that A.py can be independent of further editing and can run entirely by the input files?

Have you tried using impportlib python module for this? Give it a go, it might be what you are looking for.

Edit: specifically the importlib.import_module() function.

The docs are here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM