[Python] Another way to import

You may not know if the file exists and want to use a function in another module without using import.

You can call a fixed function from another module as an add-on. The example below is an example of importing imp.py from machnery_test.py and using test_func ().

machnery_test.py

from importlib import machinery
import os

filename = '{}/imp.py'.format(os.path.dirname(__file__))

loader = machinery.SourceFileLoader('filename', filename)
module = loader.load_module()

print(module.test_func())

同じフォルダ内のimp.py

def test_func():
    print('Test function')
    return 'Result from test_func'

output

Test function
Result from test_func

Recommended Posts

[Python] Another way to import
Easy way to customize Python import
[Python] How to import the library
Python to switch from another language
Updated to Python 2.7.9
Python module import
Import python script
Easy way to use Wikipedia in Python
A way to understand Python duck typing
"Backport" to python 2
Summarize Python import
The fastest way for beginners to master Python
Easy way to use Python 2.7 on Cent OS 6
Summary of how to import files in Python 3
Import Excel file from Python (register to DB)
The easiest way to synthesize speech with python
A clever way to time processing in Python
Excel X Python The fastest way to work
The easiest way to use OpenCV with python
Introduction to Python with Atom (on the way)
Difference in object ID due to import in Python
An easy way to call Java from Python
How to install Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Python from or import
Rewrite Python2 code to Python3 (2to3)
How to install python
python decorator to retry
Introduction to Python language
Introduction to OpenCV (python)-(2)
Note to daemonize python
unable to import django
Introducing Python 2.7 to CentOS 6.6
Connect python to mysql
Import tsv with Python
[Python MinMaxScaler] Normalize to 0 ~ 1
How to use import
Easy way to check the source of Python modules
[Reintroduction to python] How to import via the parent directory
Backtrader How to import an indicator from another file
An easy way to create an import module with jupyter
What to do when "cannot import name xxx" [Python]
[Introduction to Udemy Python3 + Application] 68. Import statement and AS
Connect to BigQuery with Python
[2020.8 latest] How to install Python
[python] Convert date to string
Post from Python to Slack
I want to specify another version of Python with pyvenv
How to install Python [Windows]
Post to vim → Python → Slack
Introduction to Python Django (2) Win
To flush stdout in Python
Convert numpy int64 to python int
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
Cheating from PHP to Python
Dynamically import scripts in Python
Import vtk with brew python
Try to understand Python self
Python notes to forget soon