2016-10-23 3 views
0

저는 Python3에 대한 방법을 가르쳐 왔습니다. 나는 획득 한 기술을 훈련시키고 명령 행 백업 프로그램을 작성하려고했습니다. 기본 백업을 저장하고 Shelve 모듈을 사용하여 위치를 저장하려고하는데 프로그램을 닫거나 다시 시작할 때마다 변수를 잊어 버리는 것 같습니다. 난 그냥 그 후 기능을 변수를 저장하고 호출이 함수를 호출 할 때마다Shelve가 보유하고있는 변수를 잊어 버렸음

def WorkShelf(key, mode='get', variable=None): 
    """Either stores a variable to the shelf or gets one from it. 
    Possible modes are 'store' and 'get'""" 
    config = shelve.open('Config') 

    if mode.strip() == 'get': 
     print(config[key]) 
     return config[key] 

    elif mode.strip() == 'store': 
     config[key] = variable 
     print(key,'holds',variable) 

    else: 
     print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'") 

    config.close() 

그래서, 그것은 완벽하게 작동합니다 :

다음은 선반과 함께 작동하는 주요 기능입니다. 수동으로 선반에 액세스하려고했는데 모든 것이 있습니다. 내가 스크립트를 다시 시작한 후 선반에서 내 변수를 얻을 때

WorkShelf('BackUpPath','store', bupath) 
WorkShelf('Path2BU', 'store', path) 

문제는 온다 : 이 변수를 저장하는 데 사용되는 코드입니다. 이 코드 :

Traceback (most recent call last): 
    File "C:\Python35-32\lib\shelve.py", line 111, in __getitem__ 
    value = self.cache[key] 
KeyError: 'Path2BU' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<pyshell#2>", line 1, in <module> 
    config['Path2BU'] 
    File "C:\Python35-32\lib\shelve.py", line 113, in __getitem__ 
    f = BytesIO(self.dict[key.encode(self.keyencoding)]) 
    File "C:\Python35-32\lib\dbm\dumb.py", line 141, in __getitem__ 
    pos, siz = self._index[key]  # may raise KeyError 
KeyError: b'Path2BU 

는 기본적으로,이 내가 ShelveObject [ 'ThisKeyDoesNotExist를'] 호출하여 재현 할 수있는 오류입니다 :

config = shelve.open('Config') 
path = config['Path2BU'] 
bupath = config['BackUpPath'] 

날이 오류를 제공합니다.

저는 입니다. 실제로는이 손실되었습니다. 수동으로 선반을 만들려고하면 닫고 다시 액세스 할 수 있습니다 (이전에 오류가 발생 했음에도 불구하고). 나는 이것에 관한 모든 글을 읽었고, 선반 부패에 대해 생각했다. (매번 일어날 가능성은별로 없다.) 그리고 나는 약 20 번 내 스크립트 A ~ Z를 읽었다.

어떤 도움을 주셔서 감사합니다. (그리고 이번에는 올바른 질문을 던지기를 바랍니다.)


편집


좋아이 그래서는 나를 미치게하고있다. Isolation WorkShelf()는 다음과 같이 완벽하게 작동합니다.

import shelve 

    def WorkShelf(key, mode='get', variable=None): 
     """Either stores a variable to the shelf or gets one from it. 
     Possible modes are 'store' and 'get'""" 
     config = shelve.open('Config') 

     if mode.strip() == 'get': 
      print(config[key]) 
      return config[key] 

     elif mode.strip() == 'store': 
      config[key] = variable 
      print(key,'holds',variable) 

     else: 
      print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'") 

     config.close() 

    if False: 
     print('Enter path n1: ') 
     path1 = input("> ") 
     WorkShelf('Path1', 'store', path1) 

     print ('Enter path n2: ') 
     path2 = input("> ") 
     WorkShelf('Path2', 'store', path2) 

    else: 
     path1, path2 = WorkShelf('Path1'), WorkShelf('Path2') 
     print (path1, path2) 

아무 문제없이 완벽합니다.

하지만 스크립트에서 동일한 함수를 사용하면이 출력이 표시됩니다. 그것은 기본적으로 이 쉘브 파일 ('이 키는이 변수를 포함하고 있습니다'메시지)에 변수를 쓰는 것을 말합니다. 다시 시작할 때 사용하는 것과 동일한 코드로 호출 할 수도 있습니다. 그러나 프로그램을 리셋 한 후 그들을 호출하면 모두 '당신은 m8에 대해 이야기하고 있습니까? 나는 결코 이것들을 구하지 않았다.

Welcome to this backup manager. 
We will walk you around creating your backup and backup preferences 

What directory would you like to backup? 
Enter path here: W:\Users\Damien\Documents\Code\Code Pyth 
Would you like to se all folders and files at that path? (enter YES|NO) 
> n 


Okay, let's proceed. 
Where would you like to create your backup? 
Enter path here: N:\ 

Something already exists there: 
19 folders and 254 documents 

Would you like to change your location? 
> n 
Would you like to save this destination (N:\) as your default backup location ? That way you don't have to type it again. 
> y 
BackUpPath holds N:\ 

If you're going to be backing the same data up we can save the files location W:\Users\Damien\Documents\Code\Code Pyth so you don't have to type all the paths again. 
Would you like me to remember the backup file's location? 
> y 
Path2BU holds W:\Users\Damien\Documents\Code\Code Pyth 
>>> 
======== RESTART: W:\Users\Damien\Documents\Code\Code Pyth\Backup.py ======== 
Welcome to this backup manager. 
Traceback (most recent call last): 
    File "C:\Python35-32\lib\shelve.py", line 111, in __getitem__ 
    value = self.cache[key] 
KeyError: 'Path2BU' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "W:\Users\Damien\Documents\Code\Code Pyth\Backup.py", line 198, in <module> 
    path, bupath = WorkShelf('Path2BU'), WorkShelf('BackUpPath') 
    File "W:\Users\Damien\Documents\Code\Code Pyth\Backup.py", line 165, in WorkShelf 
    print(config[key]) 
    File "C:\Python35-32\lib\shelve.py", line 113, in __getitem__ 
    f = BytesIO(self.dict[key.encode(self.keyencoding)]) 
    File "C:\Python35-32\lib\dbm\dumb.py", line 141, in __getitem__ 
    pos, siz = self._index[key]  # may raise KeyError 
KeyError: b'Path2BU' 

도와주세요. 저는 미쳐 가고 텍스트 파일에서 변수를 저장하고 가져올 수있는 수업을 개발할 수 있습니다.

답변

0

좋아, 그래서 나는 잘못 된 것을 발견했다.

설치 코드에 os.chdir()이 있습니다. 설치가 끝나고 설정 파일을 열길 원할 때마다 현재 디렉토리를 보게 될 것이지만 선반은 설정에서 가리킨 디렉토리 os.chdir()에 있습니다.

실제 이유가있는 디렉토리에 빈 선반이 생겼습니다.그 날 디버깅 하루.

오늘은 모두를위한 것입니다.

관련 문제