2017-12-21 1 views
1

파이썬이 제 일을하고 있습니다. 몇 가지 모듈을로드하고 클래스를 동적으로 인스턴스화하는 것이 매우 어려울 수 있다고 생각하지 않습니다. 여기에 몇 가지 다른 질문을 읽었지만 제공되는 솔루션 중 아무 것도 나를 위해 작동하지 않는 것 같습니다.동적으로 클래스를로드하고 참조를 얻으십시오.

내 폴더 구조

./coin.py 
./exchanges/ 
    /bittrex.py (contains Bittrex class) 
    /kraken.py (contains Kraken class) 
    ... 

내 목표

, 어떤 해키 수단으로 약간의 코드와 않고, 동적으로 이러한 각 모듈을 가져 클래스에 대한 참조 내를 얻으려면 그래서 나는 그것들을 인스턴스화하고 속성을 얻을 수 있습니다.

내 현재 코드

import glob, exchanges, dirfiles, isfile, inspect 

dirfiles = glob.glob(dirname(__file__) + "/exchanges/*.py") 
__all__ = [ basename(f)[:-3] for f in dirfiles if isfile(f) and not f.endswith('__init__.py')] 

class Indicator(object): 
    def __init__(self): 
     for exchange in __all__: 
      class_name = exchange.capitalize() 
      class_ = getattr(exchange, class_name) 

      self.EXCHANGES.append({ 
       'code': exchange, 
       'name': class_name, 
       'instance': class_(self) 
      }) 

그러나 위의 코드와 나는 항상 시도는 문자열로 내 의도 클래스 참조를 해석하여 결국 한 여러 가지 순열.

+0

동적으로 클래스 이름이 a = 'Bittrex'와 같이 변수에 저장된다는 것을 의미합니까 ?? 덕분에 –

답변

1
Importlib 동적 모듈과 패키지의로드 허용

os.listdir는 파일을 찾는 단순화

import os 
import importlib 

for p in os.listdir('exchanges'): 
    if p[-3:] == '.py' and p != '__init__.py': 
     module_ = importlib.import_module("exchanges.%s" % p[:-3]) 
     class_ = getattr(module_, class_name) 

     self.EXCHANGES.append({ 
      'code': exchange, 
      'name': class_name, 
      'instance': class_(self) 
     }) 

난 당신의 코드에서 capitalze에 대해 확실 해요. 그것이 각 파일의 함수라면, 다음과 같이 실행할 수 있습니다 :

capitalize = getattr(module_, 'capitalize') 
class_name = capitalize() 
+0

. 나는이 일을 시도했지만 import_module() 함수는 'exchange'의 네임 스페이스 객체를 반환하지만 모듈의 객체는 반환하지 않습니다. 그것은 지금 일하는 것처럼 보입니다 (당신이 전에 며칠 동안 있지 않아도 SO에 게시 한 후에도 해결책을 찾을 수 있습니다). 'capitalize()'는 대문자로 쓰여진 클래스를 적재하는 것입니다. – bluppfisk

+0

importlib에서 필자가 필요로하는 모든 작업을 위해'__import __()'문에서'fromlist = [exchange]'가 필요하다는 것을 알게되었습니다. 고맙습니다! – bluppfisk

+0

제외 할 파일이 더 많은 경우 조건을 확장해야한다고 생각합니다. 불행히도, 나는 더 자세한 내용이 없기 때문에 더 잘 판단 할 수는 없습니다. – clemens

0

importlib 모듈을 사용할 수 있습니다.

디렉토리 구조 : dsp.py의

Current_Dir 
    | 
    |---qwerty.py 
    | 
    |---dinesh 
      | 
      |--dsp.py -->> This file has class 'call_me' 

코드 : qwerty.py의

class call_me(object): 

    def __init__(self): 
     pass 

    def run(self): 
     print("Dinesh") 

코드 :

예를 아래에

확인하시기 바랍니다 0

import sys 
import os 
import importlib 

lib_path = os.getcwd() + os.sep + 'dinesh' 
sys.path.insert(0,lib_path) 

mod = importlib.import_module('dsp') 
a = getattr(mod,'call_me') 
s = a() 
s.run() 

출력

C:\Users\punddin\PycharmProjects\demo>python qwerty.py 
Dinesh 
관련 문제