0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python] importする別の方法

Posted at

ファイルが存在しているか不明で、importを利用せず別module内の関数を使用したい場合があります。

アドオン的に別moduleから決まった関数を呼び出せます。下記の例は、machnery_test.pyからimp.pyををインポートして、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'

出力

Test function
Result from test_func
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?