Hi I am trying open a record from a shelve db I Know that it stops working at copy = db[opened]

But why please help ASAP

#*****START VARIABEL BLOCK*****
#file = the database/shelf file
#db = the database/shelf object 
#tapp = to be appended/recorded to the database
#keys = a list of all the database's keys
#flag = if True = that record/rey already exists, if False = that record/rey does not exist
#Name = 1st field
#note = 2nd field
#strkey=str(key)
#*****END VARIABEL BLOCK*****

def on_OpenKey_command(self, event):

    try:
        global db

        opened = str(self.components.key.text)

        copy = db[opened]
        tapp = []
        tapp = easygui.multenterbox(msg = "Edit the properties,then press Ok to save.", title = "DataBank|Edit", fields = ("KEY","1","2","3","4","5","6","7","8","10"), values = copy)
        tapp = copy
        KEY = tapp[0]
        KEY = str(KEY)

        db[KEY] = tapp
        self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
        self.components.dbItems.items = Items


        Items = db.values()

        self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
        self.components.dbItems.items = Items

    except: 


        global db
        tapp = []
        tapp = easygui.multenterbox("Edit the properties,then press Ok to save.","DataBank|Edit", ("KEY","1","2","3","4","5","6","7","8","10"))
        key  = tapp[0]
        keys = str(key)
        db[keys] = tapp
        Items = str(db.values())

        Items = db.values()

        self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
        self.components.dbItems.items = Items

Dani AI

Generated

A few focused checks and small fixes will make the failure at the point where you do the lookup much easier to diagnose and eliminate.

Quick checklist (do these first)

  • Print a full traceback instead of using a bare except so you see the real exception (KeyError, NameError, TypeError, etc.).
  • Print the shelf and key right before the lookup: the type of db, repr(key), and list(db.keys()) (or list(db)), to confirm the key really exists and is the expected string.
  • Guard the lookup so it does not raise unexpectedly (use membership test or get) and handle GUI cancel returns (multenterbox can return None).

Minimal safe patterns

import traceback

key = str(self.components.key.text).strip()
try:
    if key not in db:
        easygui.msgbox("No record found for {!r}".format(key))
    else:
        record = db[key]
except KeyError:
    easygui.msgbox("Key error for {!r}".format(key))
except Exception:
    traceback.print_exc()
    raise

Or use record = db.get(key) and check for None before using it.

Other likely causes and fixes

  • Uninitialized/closed db: the intermittent success you mentioned () looks like a race where db is not reliably opened. Make db an attribute (e.g., self.db) and ensure you open it before any UI action.
  • Keys: shelve keys must be strings; trim whitespace and use repr() when debugging to reveal hidden characters.
  • GUI cancel: easygui.multenterbox can return None — treat that case before assigning or writing back.
  • Avoid writeback=True unless needed (it masks in-place changes and uses memory).
  • Replace repeated UI-update blocks with one refresh_items() helper that reads list(self.db.values()) and updates the grid.

Follow advice: add prints/tests around the failing line, capture the traceback, and then post the traceback if you still need help. These steps will show whether the problem is a missing key, an un-opened shelf, a bad key string, or a concurrency/locking issue.

Recommended Answers

All 4 Replies

If it stops working, there must be a traceback or something. Can you post the traceback ? Also your code doesn't show what is db nor its content, perhaps you could attach the shelve file in a zipped form. The 'global db' statements are suspicious. At best, they serve no purpose.

here is the full code:

#!/python-32
# -*- coding: utf-8 -*-
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is data-bank.
#
# The Initial Developer of the Original Code is
# Samarth Agarwal.
# Portions created by the Initial Developer are Copyright (C) 2011
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
#***** END LICENSE BLOCK *****
#
#*****START VARIABEL BLOCK*****
#file = the database/shelf file
#db = the database/shelf object 
#tapp = to be appended/recorded to the database
#keys = a list of all the database's keys
#flag = if True = that record/rey already exists, if False = that record/rey does not exist
#Name = 1st field
#note = 2nd field
#strkey=str(key)
#*****END VARIABEL BLOCK*****



#******Imports all the modules it needs(V)*****
import shelve
from PythonCard import model
import easygui
import os
#******Imports all the modules it needs(^)*****
Version = 2.0
#


#***********The main program(V)****************************************************************************************3        
class MainWindow(model.Background):
    #self.components.del.visible = False
    #self.components.del.enabled = False 
    
    def on_About_command(self, event):
        global db
        try:
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
        except:
            pass

        About = open("README.txt", "r")
        easygui.textbox(msg="About DataBank\nVersion %i \nCopyright 2011 Samarth Agarwal" % Version, title="DataBank|About", text=About)
        About.close()
    def on_License_command(self, event):
        global db
        try:
            Items = db.values()
            
            self.components.dbItems.columnHeadings = self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
        except:
            pass
        License = open("License.txt", "r")
        easygui.textbox(msg="About DataBank\nVersion %i \nCopyright 2011 Samarth Agarwal" % Version, title="DataBank|About", text=License)
        License.close()
        
        
#***********Creates a new db/opens db/Saves DB(V)*************  
    
    def on_Newdb_command(self, event):
        global db
        
        try:
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
        except:
            pass
        file = easygui.filesavebox(msg = "Where do you want to save your database??",  title = "DATABANK|NewDb", default = "*.dat", filetypes = ["*.dat"] )
        try:
            db = shelve.open(file, writeback=True)
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
          
        except:
            pass
        
    def on_Opendb_command(self, event):
        global db
        
        
        try:
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
            
        except:
            pass
        file = easygui.fileopenbox(msg = "What database do you want to open??",  title = "DATABANK|OpenDB", default = "*.dat", filetypes = ["*.dat"] )
        try:
            db = shelve.open(file, writeback=True)
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
            
        except:
            pass
        
    
    
    
    def on_Savedb_command(self, event):
        global db
        
        try:
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
        except:
            pass
        try:
            db.sync()
            easygui.msgbox(msg="Sync Sucssful",  title="Sync|DataBank")
                    
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items
            
        except:
            easygui.exceptionbox(msg="An ERROR occurred ,if this error continues to occurred then file a issue on: http://code.google.com/p/data-bank/ and reproduce the error message below:", title="ERROR|DataBank")
     

    
            
    
        


#***********Creates a new db/opens db(^)*************    


#******************Saves A record/Opens a recored/Creates a record(V)    



 


    
    def on_OpenKey_command(self, event):
        
        try:
            global db
            
            opened = self.components.key.text
            openedstr = str(opened)
            copy = db[opened]
            tapp = []
            tapp = easygui.multenterbox(msg = "Edit the properties,then press Ok to save.", title = "DataBank|Edit", fields = ("KEY","1","2","3","4","5","6","7","8","10"), values = copy)
            tapp = copy
            KEY = tapp[0]
            KEY = str(KEY)

            db[KEY] = tapp
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items

           
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items

        except: 
            
            
            global db
            tapp = []
            tapp = easygui.multenterbox("Edit the properties,then press Ok to save.","DataBank|Edit", ("KEY","1","2","3","4","5","6","7","8","10"))
            key  = tapp[0]
            keys = str(key)
            db[keys] = tapp
            Items = str(db.values())
            
            Items = db.values()
            
            self.components.dbItems.columnHeadings = [['KEY'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9'], ['10'],['11']]
            self.components.dbItems.items = Items

            
            

     
    

#******************Saves A record/Opens a recored/Creates a record(^)
    
#******The main program(^)*********************************************************************************************3

app = model.Application(MainWindow) #The apps instance
try:
    app.MainLoop() #the main loop
except:
    easygui.exceptionbox(msg="An ERROR occurred ,if this error continues to occurred then file a issue on: http://code.google.com/p/data-bank/ and reproduce the error message below:", title="ERROR|DataBank")

Well, if the error is at line 178, you could perhaps add tests before that line: check that db is a Shelf, check that it has the key 'opened', print the key and whole content of the shelf, etc. Also print a message after line 178 to see if the program reaches this point, etc.

Your program contains many repeated blocks, like line 58-61. Write a function to execute these 3 lines and call this function instead of repeating the lines of code. Also a global db is not a good idea, why not have a member ?

I have tried Printing 1,2,3 etc after every line thats how I got to the point of line 178 being the problem but for some reason after a few fails It works properly

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.