cli.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  18. #============================================================================
  19. import pwman
  20. import pwman.exchange.importer as importer
  21. import pwman.exchange.exporter as exporter
  22. import pwman.util.generator as generator
  23. from pwman.data.nodes import Node
  24. from pwman.data.tags import Tag
  25. from pwman.util.crypto import CryptoEngine, CryptoBadKeyException, \
  26. CryptoPasswordMismatchException
  27. from pwman.util.callback import Callback
  28. import pwman.util.config as config
  29. import re
  30. import sys
  31. import os
  32. import struct
  33. import getpass
  34. import cmd
  35. import traceback
  36. import time
  37. import select as uselect
  38. if sys.platform != 'win32':
  39. import tty
  40. import termios
  41. import fcntl
  42. try:
  43. import readline
  44. _readline_available = True
  45. except ImportError, e:
  46. _readline_available = False
  47. class CLICallback(Callback):
  48. def getinput(self, question):
  49. return raw_input(question)
  50. def getsecret(self, question):
  51. return getpass.getpass(question + ":")
  52. class ANSI(object):
  53. Reset = 0
  54. Bold = 1
  55. Underscore = 2
  56. Black = 30
  57. Red = 31
  58. Green = 32
  59. Yellow = 33
  60. Blue = 34
  61. Magenta = 35
  62. Cyan = 36
  63. White = 37
  64. class PwmanCli(cmd.Cmd):
  65. def error(self, exception):
  66. if (isinstance(exception, KeyboardInterrupt)):
  67. print
  68. else:
  69. # traceback.print_exc()
  70. print "Error: %s " % (exception)
  71. def do_EOF(self, args):
  72. return self.do_exit(args)
  73. def do_exit(self, args):
  74. print
  75. try:
  76. self._db.close()
  77. except Exception, e:
  78. self.error(e)
  79. return True
  80. def get_ids(self, args):
  81. ids = []
  82. rx =re.compile(r"^(\d+)-(\d+)$")
  83. idstrs = args.split()
  84. for i in idstrs:
  85. m = rx.match(i)
  86. if m == None:
  87. try:
  88. ids.append(int(i))
  89. except ValueError, e:
  90. self._db.clearfilter()
  91. self._db.filter([Tag(i)])
  92. ids += self._db.listnodes()
  93. else:
  94. ids += range(int(m.group(1)),
  95. int(m.group(2))+1)
  96. return ids
  97. def get_filesystem_path(self, default=""):
  98. return getinput("Enter filename: ", default)
  99. def get_username(self, default=""):
  100. return getinput("Username: ", default)
  101. def get_password(self, default=""):
  102. password = getpassword("Password (Blank to generate): ", _defaultwidth,\
  103. False)
  104. if len(password) == 0:
  105. length = getinput("Password length (default 7): ", "7")
  106. length = int(length)
  107. numerics = config.get_value("Generator", "numerics") == 'true'
  108. leetify = config.get_value("Generator", "leetify") == 'true'
  109. (password, dumpme) = generator.generate_password(length, length, \
  110. True, leetify, numerics)
  111. print "New password: %s" % (password)
  112. return password
  113. else:
  114. return password
  115. def get_url(self, default=""):
  116. return getinput("Url: ", default)
  117. def get_notes(self, default=""):
  118. return getinput("Notes: ", default)
  119. def get_tags(self, default=[]):
  120. defaultstr = ''
  121. if len(default) > 0:
  122. for t in default:
  123. defaultstr += "%s " % (t.get_name())
  124. else:
  125. tags = self._db.currenttags()
  126. for t in tags:
  127. defaultstr += "%s " % (t.get_name())
  128. strings = []
  129. tags = self._db.listtags(True)
  130. for t in tags:
  131. strings.append(t.get_name())
  132. def complete(text, state):
  133. count = 0
  134. for s in strings:
  135. if s.startswith(text):
  136. if count == state:
  137. return s
  138. else:
  139. count += 1
  140. taglist = getinput("Tags: ", defaultstr, complete)
  141. tagstrings = taglist.split()
  142. tags = []
  143. for tn in tagstrings:
  144. tags.append(Tag(tn))
  145. return tags
  146. def print_node(self, node):
  147. width = str(_defaultwidth)
  148. print "Node %d." % (node.get_id())
  149. print ("%"+width+"s %s") % (typeset("Username:", ANSI.Red),
  150. node.get_username())
  151. print ("%"+width+"s %s") % (typeset("Password:", ANSI.Red),
  152. node.get_password())
  153. print ("%"+width+"s %s") % (typeset("Url:", ANSI.Red),
  154. node.get_url())
  155. print ("%"+width+"s %s") % (typeset("Notes:", ANSI.Red),
  156. node.get_notes())
  157. print typeset("Tags: ", ANSI.Red),
  158. for t in node.get_tags():
  159. print "%s " % t.get_name(),
  160. print
  161. def heardEnter():
  162. i,o,e = uselect.select([sys.stdin],[],[],0.0001)
  163. for s in i:
  164. if s == sys.stdin:
  165. input = sys.stdin.readline()
  166. return True
  167. return False
  168. def heardEnterWin():
  169. import msvcrt
  170. c = msvcrt.kbhit()
  171. if c == 1:
  172. ret = msvcrt.getch()
  173. if ret is not None:
  174. return True
  175. return False
  176. def waituntil_enter(somepredicate,timeout, period=0.25):
  177. mustend = time.time() + timeout
  178. while time.time() < mustend:
  179. cond = somepredicate()
  180. if cond:
  181. break
  182. time.sleep(period)
  183. self.do_cls('')
  184. if sys.platform != 'win32':
  185. print "Type Enter to flush screen (autoflash in 5 sec.)"
  186. waituntil_enter(heardEnter(), 5)
  187. else:
  188. print "Press any key to flush screen (autoflash in 5 sec.)"
  189. waituntil_enter(heardEnterWin, 5)
  190. def do_tags(self, arg):
  191. tags = self._db.listtags()
  192. if len(tags) > 0:
  193. tags[0].get_name() # hack to get password request before output
  194. print "Tags: ",
  195. if len(tags) == 0:
  196. print "None",
  197. for t in tags:
  198. print "%s " % (t.get_name()),
  199. print
  200. def complete_filter(self, text, line, begidx, endidx):
  201. strings = []
  202. enc = CryptoEngine.get()
  203. if not enc.alive():
  204. return strings
  205. tags = self._db.listtags()
  206. for t in tags:
  207. name = t.get_name()
  208. if name.startswith(text):
  209. strings.append(t.get_name())
  210. return strings
  211. def do_filter(self, args):
  212. tagstrings = args.split()
  213. try:
  214. tags = []
  215. for ts in tagstrings:
  216. tags.append(Tag(ts))
  217. self._db.filter(tags)
  218. tags = self._db.currenttags()
  219. print "Current tags: ",
  220. if len(tags) == 0:
  221. print "None",
  222. for t in tags:
  223. print "%s " % (t.get_name()),
  224. print
  225. except Exception, e:
  226. self.error(e)
  227. def do_clear(self, args):
  228. try:
  229. self._db.clearfilter()
  230. except Exception, e:
  231. self.error(e)
  232. def do_e(self, arg):
  233. self.do_edit(arg)
  234. def do_edit(self, arg):
  235. ids = self.get_ids(arg)
  236. for i in ids:
  237. try:
  238. i = int(i)
  239. node = self._db.getnodes([i])[0]
  240. menu = CliMenu()
  241. print "Editing node %d." % (i)
  242. menu.add(CliMenuItem("Username", self.get_username,
  243. node.get_username,
  244. node.set_username))
  245. menu.add(CliMenuItem("Password", self.get_password,
  246. node.get_password,
  247. node.set_password))
  248. menu.add(CliMenuItem("Url", self.get_url,
  249. node.get_url,
  250. node.set_url))
  251. menu.add(CliMenuItem("Notes", self.get_notes,
  252. node.get_notes,
  253. node.set_notes))
  254. menu.add(CliMenuItem("Tags", self.get_tags,
  255. node.get_tags,
  256. node.set_tags))
  257. menu.run()
  258. self._db.editnode(i, node)
  259. except Exception, e:
  260. self.error(e)
  261. def do_import(self, arg):
  262. try:
  263. args = arg.split()
  264. if len(args) == 0:
  265. types = importer.Importer.types()
  266. type = select("Select filetype:", types)
  267. imp = importer.Importer.get(type)
  268. file = getinput("Select file:")
  269. imp.import_data(self._db, file)
  270. else:
  271. for i in args:
  272. types = importer.Importer.types()
  273. type = select("Select filetype:", types)
  274. imp = importer.Importer.get(type)
  275. imp.import_data(self._db, i)
  276. except Exception, e:
  277. self.error(e)
  278. def do_export(self, arg):
  279. try:
  280. nodes = self.get_ids(arg)
  281. types = exporter.Exporter.types()
  282. type = select("Select filetype:", types)
  283. exp = exporter.Exporter.get(type)
  284. file = getinput("Select output file:")
  285. if len(nodes) > 0:
  286. b = getyesno("Export nodes %s?" % (nodes), True)
  287. if not b:
  288. return
  289. exp.export_data(self._db, file, nodes)
  290. else:
  291. nodes = self._db.listnodes()
  292. tags = self._db.currenttags()
  293. tagstr = ""
  294. if len(tags) > 0:
  295. tagstr = " for "
  296. for t in tags:
  297. tagstr += "'%s' " % (t.get_name())
  298. b = getyesno("Export all nodes%s?" % (tagstr), True)
  299. if not b:
  300. return
  301. exp.export_data(self._db, file, nodes)
  302. print "Data exported."
  303. except Exception, e:
  304. self.error(e)
  305. def do_h(self, arg):
  306. self.do_help(arg)
  307. def do_n(self, arg):
  308. self.do_new(arg)
  309. def do_new(self, arg):
  310. try:
  311. username = self.get_username()
  312. password = self.get_password()
  313. url = self.get_url()
  314. notes = self.get_notes()
  315. node = Node(username, password, url, notes)
  316. tags = self.get_tags()
  317. node.set_tags(tags)
  318. self._db.addnodes([node])
  319. print "Password ID: %d" % (node.get_id())
  320. except Exception, e:
  321. self.error(e)
  322. def do_p(self, arg):
  323. self.do_print(arg)
  324. def do_print(self, arg):
  325. for i in self.get_ids(arg):
  326. try:
  327. node = self._db.getnodes([i])
  328. self.print_node(node[0])
  329. except Exception, e:
  330. self.error(e)
  331. def do_rm(self, arg):
  332. self.do_delete(arg)
  333. def do_delete(self, arg):
  334. ids = self.get_ids(arg)
  335. try:
  336. nodes = self._db.getnodes(ids)
  337. for n in nodes:
  338. b = getyesno("Are you sure you want to delete '%s@%s'?"
  339. % (n.get_username(), n.get_url()), False)
  340. if b == True:
  341. self._db.removenodes([n])
  342. print "%s@%s deleted" % (n.get_username(), n.get_url())
  343. except Exception, e:
  344. self.error(e)
  345. def do_l(self, args):
  346. self.do_list(args)
  347. def do_ls(self, args):
  348. self.do_list(args)
  349. def do_list(self, args):
  350. if len(args.split()) > 0:
  351. self.do_clear('')
  352. self.do_filter(args)
  353. try:
  354. if sys.platform != 'win32':
  355. rows, cols = gettermsize()
  356. else:
  357. rows,cols = 18, 80 # fix this !
  358. nodeids = self._db.listnodes()
  359. nodes = self._db.getnodes(nodeids)
  360. cols -= 8
  361. i = 0
  362. for n in nodes:
  363. tags=n.get_tags()
  364. tagstring = ''
  365. first = True
  366. for t in tags:
  367. if not first:
  368. tagstring += ", "
  369. else:
  370. first=False
  371. tagstring += t.get_name()
  372. name = "%s@%s" % (n.get_username(), n.get_url())
  373. name_len = cols * 2 / 3
  374. tagstring_len = cols / 3
  375. if len(name) > name_len:
  376. name = name[:name_len-3] + "..."
  377. if len(tagstring) > tagstring_len:
  378. tagstring = tagstring[:tagstring_len-3] + "..."
  379. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  380. print typeset(fmt % (n.get_id(), name, tagstring),
  381. ANSI.Yellow, False)
  382. i += 1
  383. if i > rows-2:
  384. i = 0
  385. c = getonechar("Press <Space> for more, or 'Q' to cancel")
  386. if c == 'q':
  387. break
  388. except Exception, e:
  389. self.error(e)
  390. def do_forget(self, args):
  391. try:
  392. enc = CryptoEngine.get()
  393. enc.forget()
  394. except Exception,e:
  395. self.error(e)
  396. def do_passwd(self, args):
  397. try:
  398. self._db.changepassword()
  399. except Exception, e:
  400. self.error(e)
  401. def do_set(self, args):
  402. argstrs = args.split()
  403. try:
  404. if len(argstrs) == 0:
  405. conf = config.get_conf()
  406. for s in conf.keys():
  407. for n in conf[s].keys():
  408. print "%s.%s = %s" % (s, n, conf[s][n])
  409. elif len(argstrs) == 1:
  410. r = re.compile("(.+)\.(.+)")
  411. m = r.match(argstrs[0])
  412. if m is None or len(m.groups()) != 2:
  413. print "Invalid option format"
  414. self.help_set()
  415. return
  416. print "%s.%s = %s" % (m.group(1), m.group(2),
  417. config.get_value(m.group(1), m.group(2)))
  418. elif len(argstrs) == 2:
  419. r = re.compile("(.+)\.(.+)")
  420. m = r.match(argstrs[0])
  421. if m is None or len(m.groups()) != 2:
  422. print "Invalid option format"
  423. self.help_set()
  424. return
  425. config.set_value(m.group(1), m.group(2), argstrs[1])
  426. else:
  427. self.help_set()
  428. except Exception, e:
  429. self.error(e)
  430. def do_save(self, args):
  431. argstrs = args.split()
  432. try:
  433. if len(argstrs) > 0:
  434. config.save(argstrs[0])
  435. else:
  436. config.save()
  437. print "Config saved."
  438. except Exception, e:
  439. self.error(e)
  440. def do_cls(self,args):
  441. os.system('clear')
  442. ##
  443. ## Help functions
  444. ##
  445. def usage(self, string):
  446. print "Usage: %s" % (string)
  447. def help_cls(self):
  448. self.usage("cls")
  449. print "Clear the Screen from information."
  450. def help_ls(self):
  451. self.help_list()
  452. def help_list(self):
  453. self.usage("list <tag> ...")
  454. print "List nodes that match current or specified filter. ls is an alias."
  455. def help_EOF(self):
  456. self.help_exit()
  457. def help_delete(self):
  458. self.usage("delete <ID|tag> ...")
  459. print "Deletes nodes. rm is an alias."
  460. self._mult_id_help()
  461. def help_h(self):
  462. self.help_help()
  463. def help_help(self):
  464. self.usage("help [topic]")
  465. print "Prints a help message for a command."
  466. def help_e(self):
  467. self.help_edit()
  468. def help_n(self):
  469. self.help_new()
  470. def help_p(self):
  471. self.help_print()
  472. def help_l(self):
  473. self.help_list()
  474. def help_edit(self):
  475. self.usage("edit <ID|tag> ... ")
  476. print "Edits a nodes."
  477. self._mult_id_help()
  478. def help_import(self):
  479. self.usage("import [filename] ...")
  480. print "Imports a nodes from a file."
  481. def help_export(self):
  482. self.usage("export <ID|tag> ... ")
  483. print "Exports a list of ids to an external format. If no IDs or tags are specified, then all nodes under the current filter are exported."
  484. self._mult_id_help()
  485. def help_new(self):
  486. self.usage("new")
  487. print "Creates a new node."
  488. def help_rm(self):
  489. self.help_delete()
  490. def help_print(self):
  491. self.usage("print <ID|tag> ...")
  492. print "Displays a node. ",
  493. self._mult_id_help()
  494. def _mult_id_help(self):
  495. print "Multiple ids and nodes can be specified, separated by a space. A range of ids can be specified in the format n-N. e.g. '10-20' would specify all nodes having ids from 10 to 20 inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar' would yield to all nodes with tag 'foo', node 2 and all nodes with tag 'bar'."
  496. def help_exit(self):
  497. self.usage("exit")
  498. print "Exits the application."
  499. def help_save(self):
  500. self.usage("save [filename]")
  501. print "Saves the current configuration to [filename]. If no filename is given, the configuration is saved to the file from which the initial configuration was loaded."
  502. def help_set(self):
  503. self.usage("set [configoption] [value]")
  504. print "Sets a configuration option. If no value is specified, the current value for [configoption] is output. If neither [configoption] nor [value] are specified, the whole current configuration is output. [configoption] must be of the format <section>.<option>"
  505. def help_ls(self):
  506. self.help_list()
  507. def help_passwd(self):
  508. self.usage("passwd")
  509. print "Changes the password on the database. "
  510. def help_forget(self):
  511. self.usage("forget")
  512. print "Forgets the database password. Your password will need to be reentered before accessing the database again."
  513. def help_clear(self):
  514. self.usage("clear")
  515. print "Clears the filter criteria. "
  516. def help_filter(self):
  517. self.usage("filter <tag> ...")
  518. print "Filters nodes on tag. Arguments can be zero or more tags. Displays current tags if called without arguments."
  519. def help_tags(self):
  520. self.usage("tags")
  521. print "Displays all tags in used in the database."
  522. def postloop(self):
  523. try:
  524. readline.write_history_file(self._historyfile)
  525. except Exception, e:
  526. pass
  527. def __init__(self, db):
  528. cmd.Cmd.__init__(self)
  529. self.intro = "%s %s (c) %s <%s>" % (pwman.appname, pwman.version,
  530. pwman.author, pwman.authoremail)
  531. self._historyfile = config.get_value("Readline", "history")
  532. try:
  533. enc = CryptoEngine.get()
  534. enc.set_callback(CLICallback())
  535. self._db = db
  536. self._db.open()
  537. except Exception, e:
  538. self.error(e)
  539. sys.exit(1)
  540. try:
  541. readline.read_history_file(self._historyfile)
  542. except Exception, e:
  543. pass
  544. self.prompt = "pwman> "
  545. _defaultwidth = 10
  546. def getonechar(question, width=_defaultwidth):
  547. question = "%s " % (question)
  548. print question.ljust(width),
  549. sys.stdout.flush()
  550. fd = sys.stdin.fileno()
  551. tty_mode = tty.tcgetattr(fd)
  552. tty.setcbreak(fd)
  553. try:
  554. ch = os.read(fd, 1)
  555. finally:
  556. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  557. print ch
  558. return ch
  559. def getyesno(question, defaultyes=False, width=_defaultwidth):
  560. if (defaultyes):
  561. default = "[Y/n]"
  562. else:
  563. default = "[y/N]"
  564. ch = getonechar("%s %s" % (question, default), width)
  565. if (ch == '\n'):
  566. if (defaultyes):
  567. return True
  568. else:
  569. return False
  570. elif (ch == 'y' or ch == 'Y'):
  571. return True
  572. elif (ch == 'n' or ch == 'N'):
  573. return False
  574. else:
  575. return getyesno(question, defaultyes, width)
  576. def gettermsize():
  577. s = struct.pack("HHHH", 0, 0, 0, 0)
  578. f = sys.stdout.fileno()
  579. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  580. rows, cols, width, height = struct.unpack("HHHH", x)
  581. return rows, cols
  582. def getinput(question, default="", completer=None, width=_defaultwidth):
  583. if (not _readline_available):
  584. return raw_input(question.ljust(width))
  585. else:
  586. def defaulter(): readline.insert_text(default)
  587. readline.set_startup_hook(defaulter)
  588. oldcompleter = readline.get_completer()
  589. readline.set_completer(completer)
  590. x = raw_input(question.ljust(width))
  591. readline.set_completer(oldcompleter)
  592. readline.set_startup_hook()
  593. return x
  594. def getpassword(question, width=_defaultwidth, echo=False):
  595. if echo:
  596. print question.ljust(width),
  597. return sys.stdin.readline().rstrip()
  598. else:
  599. while 1:
  600. a1 = getpass.getpass(question.ljust(width))
  601. if len(a1) == 0:
  602. return a1;
  603. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  604. if a1 == a2:
  605. return a1
  606. else:
  607. print "Passwords don't match. Try again."
  608. def typeset(text, color, bold=False, underline=False):
  609. if not config.get_value("Global", "colors") == 'yes':
  610. return text
  611. if (bold):
  612. bold = "%d;" %(ANSI.Bold)
  613. else:
  614. bold = ""
  615. if (underline):
  616. underline = "%d;" % (ANSI.Underline)
  617. else:
  618. underline = ""
  619. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  620. text, ANSI.Reset)
  621. def select(question, possible):
  622. for i in range(0, len(possible)):
  623. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  624. while 1:
  625. input = getonechar(question)
  626. if input.isdigit() and int(input) in range(1, len(possible)+1):
  627. return possible[int(input)-1]
  628. class CliMenu(object):
  629. def __init__(self):
  630. self.items = []
  631. def add(self, item):
  632. if (isinstance(item, CliMenuItem)):
  633. self.items.append(item)
  634. else:
  635. print item.__class__
  636. def run(self):
  637. while True:
  638. i = 0
  639. for x in self.items:
  640. i = i + 1
  641. current = x.getter()
  642. currentstr = ''
  643. if type(current) == list:
  644. for c in current:
  645. currentstr += ("%s " % (c))
  646. else:
  647. currentstr = current
  648. print ("%d - %-"+str(_defaultwidth)+"s %s") % (i, x.name+":",
  649. currentstr)
  650. print "%c - Finish editing" % ('X')
  651. option = getonechar("Enter your choice:")
  652. try:
  653. # substract 1 because array subscripts start at 1
  654. selection = int(option) - 1
  655. value = self.items[selection].editor(self.items[selection].getter())
  656. self.items[selection].setter(value)
  657. except (ValueError,IndexError):
  658. if (option.upper() == 'X'):
  659. break
  660. print "Invalid selection"
  661. class CliMenuItem(object):
  662. def __init__(self, name, editor, getter, setter):
  663. self.name = name
  664. self.editor = editor
  665. self.getter = getter
  666. self.setter = setter