2
3

More than 5 years have passed since last update.

子ディレクトリにある実行ファイルから、親ディレクトリのライブラリを参照するためにsys.path.appendするコードは、pyhton-fireで解決できる

Last updated at Posted at 2019-04-25

親ディレクトリにあるライブラリを使うために、実行ファイルからの相対パスを使ってimportするコードをたまに見かける。

bin/hoge.py
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import library


def hoge():
    library.echo('hoge')


if __name__ == '__main__':
    hoge()

$ python bin/hoge.py 
hoge

このコードはimport libraryの部分でWARNINGが出る。

Python | PEP 8 coding style violation

これは、親ディレクトリに実行ファイルを作り、python-fire経由で子の関数を見るようにすると綺麗に解決できる。

run.py
import fire
import bin

if __name__ == '__main__':
    fire.Fire(bin)
bin/__init__.py
from .fuga import fuga
from .hoge import hoge
bin/fuga.py
import library


def fuga():
    library.echo('fuga')
$ python run.py fuga
fuga

python-fireは、いいぞ。

サンプルコード

2
3
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
2
3