2010-06-27 4 views
0

아래에 아름다운 파이썬 예제 코드를 작성했습니다. 이제 어떻게 끝내고 프로그램을 다시 시작하면 저울의 마지막 위치를 기억할 수 있을까요?어떻게 파이썬이 설정을 기억하게합니까?

import Tkinter 

root = Tkinter.Tk() 

root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) 
root.sclX.pack(ipadx=75) 

root.resizable(False,False) 
root.title('Scale') 
root.mainloop() 

편집 :

는 다음 코드

import Tkinter 
import cPickle 


root = Tkinter.Tk() 

root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) 
root.sclX.pack(ipadx=75) 



root.resizable(False,False) 
root.title('Scale') 


with open('myconfig.pk', 'wb') as f: 
    cPickle.dump(f, root.config(), -1) 
    cPickle.dump(f, root.sclX.config(), -1) 
root.mainloop() 

하지만 시도 파일로 스케일 값을 쓰기 다음과 같은 오류

Traceback (most recent call last): 
    File "<string>", line 244, in run_nodebug 
    File "C:\Python26\pickleexample.py", line 17, in <module> 
    cPickle.dump(f, root.config(), -1) 
TypeError: argument must have 'write' attribute 

답변

4

를 얻을에 읽어 시작에. 여기에 예를 들어, 저장하고 추가 값을 복원하려는 경우에

CONFIG_FILE = '/path/to/config/file' 

root.sclX = ... 

try: 
    with open(CONFIG_FILE, 'r') as f: 
     root.sclX.set(int(f.read())) 
except IOError: # this is what happens if the file doesn't exist 
    pass 

... 
root.mainloop() 

# this needs to run when your program exits 
with open(CONFIG_FILE, 'w') as f: 
    f.write(str(root.sclX.get())) 

은 분명히 당신이 더/강력한 복잡한/복잡하게 만들 수 (약) 그것을 할 수있는 한 가지 방법은 있습니다.

+0

나는이 방법을 시도했지만 다음과 같은 오류 얻을 : 역 추적 (마지막으로 가장 최근 통화) : 파일 "", 라인 (244),에서를 run_nodebug 에서 파일 "C : \ Python26 \ pickleexample.py"파일을 열고 (CONFIG_FILE, 'w') f : IOError : [Errno 2] 해당 파일이나 디렉토리가 없습니다. '라이브러리 \\ Documents \\ T.txt ' 어떻게 파일 디렉토리를 올바르게 설정합니까? – rectangletangle

+0

아마도 생성하려는 파일의 상위 디렉토리 중 하나가 존재하지 않는다는 것을 의미합니다. 'CONFIG_FILE'에서 지정한 파일의 부모 디렉토리가 존재하는지 확인하십시오. 예를 들어,'CONFIG_FILE = 'Libraries \ Documents \ T.txt'를 설정했다면, Python 스크립트를 실행하는 디렉토리에 상대적인'Libraries \ Documents' 디렉토리가 존재하는지 확인하십시오. 절대 경로 (드라이브 문자로 시작하는 경로)를 사용하는 것이 좋습니다. 'CONFIG_FILE = 'C : \ SomeFolder \ Libraries \ Documents \ T.txt'로 설정하십시오. 그렇게 혼란스럽지 않습니다. –

1

당신은 매개 변수 예 "save.txt"를라는 파일을 작성하는 프로그램을 이야기하고 더 실행에로드 할 수 있습니다 :

어떤 "save.txt는"이 있습니까?

아니오 : 매개 변수와 함께 새로운 저장 파일을 작성하십시오. 예 : 매개 변수를 읽고 변수에 전달합니다.

매개 변수가 업데이트 된 경우 파일에서 다시 작성하십시오. (시 후속 실행에

import cPickle 
with open('myconfig.pk', 'wb') as f: 
    cPickle.dump(f, root.config(), -1) 
    cPickle.dump(f, root.sclX.config(), -1) 

과 :

나는 읽기 및 쓰기 파일 :

3

을 그냥 mainloop하기 전에 몇 가지 좋은 라이브러리가 있어야한다, 파이썬에 전문가가 아니에요하지만, .pk 파일이 이미 있음), 해당 cPickle.load 전화를 다시 가져 와서 ...config(**k)으로 설정해야합니다 (축축한 구성을 다시로드해도 안전하다는 것을 cPickle으로 확인하기 위해 몇 가지 속임수가 필요합니다).

인터프리터

help(cPickle.dump) 

의 간단한 사용은 즉시 F와 전화에 저장된 객체 교환에 의해 알렉스의 코드를 변경 시도해야 발표 할 예정이다

0

:

cPickle.dump(root.config(), f, -1) 
cPickle.dump(root.sclX.config(), f, -1) 
0

이 오브제 지속성을 Python의 멋진 모듈입니다 : shelve.

스크립트 1

import shelve 

settings = shelve.open('mySettings') 
settings['vroot_directory'] = commands.getoutput("pwd") 

스크립트 2

import shelve 

settings = shelve.open('mySettings') 
root_directory_script1 = settings['vroot_directory']) 

RGDS,

PS (두 스크립트는 같은 디렉토리에 있습니다).보다 완전한 예를 들어 gddc에 의해 내 게시물의 대답 : Importing python variables of a program after its execution

관련 문제