2009-05-15 4 views
2

변수 이름을 얻는 작은 함수를 작성하고, 존재하지 않는지 확인한 후 파일에서 (pickle을 사용하여) 전역 이름 공간으로로드하려고합니다.파이썬에서 변수로 파일로드하기

import cPickle 

# 
# Load if neccesary 
# 
def loadfile(variable, filename): 
    if variable not in globals(): 
     cmd = "%s = cPickle.load(file('%s','r'))" % (variable, filename) 
     print cmd 
     exec(cmd) in globals() 

을하지만 그것은 작동하지 않습니다 - 변수가 정의되지 않습니다

나는 파일에이를 사용했습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

2

'전역'를 사용에만 작동 문제가있다 현재 모듈. '전역'을 전달하는 대신 더 나은 방법은 'setattr'내장을 네임 스페이스에 직접 사용하는 것입니다. 즉, 인스턴스뿐만 아니라 모듈에서도 함수를 재사용 할 수 있습니다.

import cPickle 

# 
# Load if neccesary 
# 
def loadfile(variable, filename, namespace=None): 
    if module is None: 
     import __main__ as namespace 
    setattr(namespace, variable, cPickle.load(file(filename,'r'))) 

# From the main script just do: 
loadfile('myvar','myfilename') 

# To set the variable in module 'mymodule': 
import mymodule 
... 
loadfile('myvar', 'myfilename', mymodule) 

모듈 이름에 대한주의 : 메인 스크립트가 항상 모듈 주요입니다. script.py를 실행하고 '스크립트 가져 오기'를 수행하면 일반적으로 원하지 않는 별도의 코드 사본을 얻게됩니다.

2

당신은 항상 곁에 완전히 간부를 피할 수 :

 

import cPickle 

# 
# Load if neccesary 
# 
def loadfile(variable, filename): 
    g=globals() 
    if variable not in g: 
     g[variable]=cPickle.load(file(filename,'r')) 

 

편집 :은 현재 모듈의 전역에 전역을로드 물론. 매개 변수로 그들에 전달하는 가장 것 다른 모듈의 전역에 물건을로드하려면

는 :

 

import cPickle 

# 
# Load if neccesary 
# 
def loadfile(variable, filename, g=None): 
    if g is None: 
     g=globals() 
    if variable not in g: 
     g[variable]=cPickle.load(file(filename,'r')) 

# then in another module do this 
loadfile('myvar','myfilename',globals()) 
 
+0

내 파일을 execfile로로드 할 때만 작동하지만 가져 오기로로드 할 때 작동하지 않습니다. 왜 그런가요? 감사! –

+0

아마도 전역 변수는 모듈에 전역 적으로 존재하기 때문일 것입니다. –

+0

감사합니다. 모듈에서 자동으로 인터프리터의 globals()에 접근 할 수 있습니까? –

관련 문제