(Python) Shelve + try: how to search for a key and set it if it doesn't exists without repeating code?

StackOverflow https://stackoverflow.com/questions/21744792

  •  10-10-2022
  •  | 
  •  

Question

To store the user work folders permanently, I'm using shelve. And to know if the user has the folders configured I'm using a similar code 3 times:

pastaUsuario = os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH')
pastaPrincipal = pastaUsuario + '\\rev'
pastaConfig = pastaPrincipal + '\\config'

config = shelve.open(pastaConfig + '\\config.db')
try:
  pastaIsometricosSpooler = config['pastaIsometricosSpooler']
except Exception:
  config['pastaIsometricoSpooler'] = raw_input('Digite o caminho da pasta de extração do       Spooler: ')
  pastaIsometricosSpooler = config['pastaIsometricosSpooler']
finally:
  config.close()

config = shelve.open(pastaConfig + '\\config.db')  
try:
  ultimoIso = config['ultimoIso']
except Exception:
  config['ultimoIso'] = raw_input('Digite o tag do isométrico a ser revisado: ')
  ultimoIso = config['ultimoIso']
 finally:
  config.close()

config = shelve.open(pastaConfig + '\\config.db')
try:
  ultimaRev = config['ultimaRev']
except Exception:
  config['ultimaRev'] = raw_input('Digite a nova revisão: ')
  ultimaRev = config['ultimaRev']
finally:
  config.close()

How to avoid repeating the almost identical code? I tried to use the "for" statement with a list:

config = shelve.open(pastaConfig + '\\config.db')
for x in ['pastaIsometricosSpooler', 'ultimoIso', 'ultimaRev']:
  try:
    x = config[x]
  except Exception:
    config[x] = raw_input()
    x = config[x]
  finally:
    config.close()

But the variable set doesn't work because of quotes (eg.: 'ultimaRev' = config['ultimaRev'])

Sorry for my bad english!

Was it helpful?

Solution

This is probably best done by using a function rather than trying to make the same code work in a loop. Adapting what you have:

def getconfig( x, prompt ):   
  try:
    theconf= config[x]
  except Exception:
    config[x] = raw_input( prompt )
    theconf= config[x]
  return theconf

Then you can use it three times:

config = shelve.open(pastaConfig + '\\config.db')
ultimaRev = getconfig( 'ultimaRev', 'Digite a nova revisão: ')
ultimoIso = getconfig( 'ultimoIso', 'Digite o tag do' )
pastaIsometricosSpooler = getconfig('pastaIsometricosSpooler', 'Digite o caminho da' )
config.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top