Login

optparse dic action

Author:
bl4th3rsk1t3
Posted:
July 6, 2009
Language:
Python
Version:
1.0
Score:
0 (after 2 ratings)

An optparse action that let's you accept any parameters from the commandline. It stores them in another dictionary, inside the final options.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from optparse import Option

class DictOption(Option):
	"""
	A parseopt option that let's me define a dictionary through
	the commandline.
	
	optparse example:
	parser.add_option(DictOption("-p","--passwords",dest="passwords",type="string",action="dic"))
	
	Commandline usage:
	--passwords=[localhost]value,[slicehost]whatever
	
	Commandline, if spaces are needed:
	--passwords="[localhost]my Password,[slicehost]Anot erPassword"
	
	This would be defined in the final options dictionary as another dictionary:
	example 1: { 'passwords':{'localhost':'value' } }
	example 2: { 'passwords':{'localhost':'my Password', 'slicehost':'Anot erPassword' } }
	"""
	ACTIONS = Option.ACTIONS + ("dic",)
	STORE_ACTIONS = Option.STORE_ACTIONS + ("dic",)
	TYPED_ACTIONS = Option.TYPED_ACTIONS + ("dic",)
	ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("dic",)
	def take_action(self,action,dest,opt,value,values,parser):
		if action=="dic":
			vals=value.split(",")
			d={}
			for val in vals:
				p=val.split("]")
				k=p[0][1:]
				v=p[1]
				d[k]=v
			setattr(values,dest,d)
		else: Option.take_action(self, action, dest, opt, value, values, parser)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.