Dynamically import scripts in Python

In Python, scripts with ** hyphens (-) ** in their filenames cannot be imported statements. However, if you really want to import a file name with a hyphen to write a test, I found out what to do, so make a note.

__import__

** \ _ \ _ import \ _ \ _ ** takes the pathname of the file as an argument and returns the module of the file.

load-path.py


import sys
path = sys.path
>>> module = __import__("load-path")
>>> type(module)
<type 'module'>
>>> dir(module)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sys', 'path']
>>> dir.path

Now you can easily import even files with hyphens.

Use in test class

py:unit.test.py


import unittest

class Tester(unittest.TestCase):
    module = __import__("load-path")

    def setUp(self):
        for key in dir(self.module):
            setattr(self, key, getattr(self.module,key))

Recommended Posts

Dynamically import scripts in Python
Dynamically call methods in Python
Dynamically import / reload modules that have changed in Python
Import classes in jar files directly from Python scripts
Dynamically load json type in python
Dynamically define functions (methods) in Python
Quadtree in Python --2
CURL in python
[Python3] Dynamically define global variables in functions
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Python module import
How to dynamically define variables in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
Import python script
quicksort in python
nCr in python
I can't debug python scripts in Eclipse
N-Gram in Python
Template for writing batch scripts in python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
How to dynamically zero pad in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Module import and exception handling in python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
Import Error in Python3: No module named'xxxxx'
Summarize Python import
flatten in python
Summary of how to import files in Python 3
Type Python scripts to run in QGIS Processing
To dynamically replace the next method in python