end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

pythonで、任意のdirにライブラリのpathを通す

#!/usr/local/bin/perl
use strict;
use warnings;
use utf8;
use FindBin;
use File::Spec;
use lib File::Spec->catdir($FindBin::Bin, '../lib');
   :

perlでは上記のように「use lib , FindBin」を使用していましたが pythonでは、以下のように「import sys,os」や「sys.path.append()」を使うみたい。

init.py」の配備もポイントみたい

$ cat script/foo.py 
#!/usr/local/bin/python
# coding: utf-8
import sys,os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../lib')

from TestClass import TestClass

def main():
    test_obj = TestClass(3)
    print test_obj.width


if __name__ == '__main__':
    main()
$ cat lib/TestClass.py
# coding: utf-8

class TestClass(object):
    def __init__(self, width): #constractor
        self.width = width
$ tree
.
├── lib
│   ├── __init__.py
│   └── TestClass.py
└── script
     └── foo.py