/Tools/pybench/CommandLine.py

http://unladen-swallow.googlecode.com/ · Python · 634 lines · 578 code · 22 blank · 34 comment · 13 complexity · 281aa2b405a361769afcab4af8da7d90 MD5 · raw file

  1. """ CommandLine - Get and parse command line options
  2. NOTE: This still is very much work in progress !!!
  3. Different version are likely to be incompatible.
  4. TODO:
  5. * Incorporate the changes made by (see Inbox)
  6. * Add number range option using srange()
  7. """
  8. __copyright__ = """\
  9. Copyright (c), 1997-2006, Marc-Andre Lemburg (mal@lemburg.com)
  10. Copyright (c), 2000-2006, eGenix.com Software GmbH (info@egenix.com)
  11. See the documentation for further information on copyrights,
  12. or contact the author. All Rights Reserved.
  13. """
  14. __version__ = '1.2'
  15. import sys, getopt, string, glob, os, re, exceptions, traceback
  16. ### Helpers
  17. def _getopt_flags(options):
  18. """ Convert the option list to a getopt flag string and long opt
  19. list
  20. """
  21. s = []
  22. l = []
  23. for o in options:
  24. if o.prefix == '-':
  25. # short option
  26. s.append(o.name)
  27. if o.takes_argument:
  28. s.append(':')
  29. else:
  30. # long option
  31. if o.takes_argument:
  32. l.append(o.name+'=')
  33. else:
  34. l.append(o.name)
  35. return string.join(s,''),l
  36. def invisible_input(prompt='>>> '):
  37. """ Get raw input from a terminal without echoing the characters to
  38. the terminal, e.g. for password queries.
  39. """
  40. import getpass
  41. entry = getpass.getpass(prompt)
  42. if entry is None:
  43. raise KeyboardInterrupt
  44. return entry
  45. def fileopen(name, mode='wb', encoding=None):
  46. """ Open a file using mode.
  47. Default mode is 'wb' meaning to open the file for writing in
  48. binary mode. If encoding is given, I/O to and from the file is
  49. transparently encoded using the given encoding.
  50. Files opened for writing are chmod()ed to 0600.
  51. """
  52. if name == 'stdout':
  53. return sys.stdout
  54. elif name == 'stderr':
  55. return sys.stderr
  56. elif name == 'stdin':
  57. return sys.stdin
  58. else:
  59. if encoding is not None:
  60. import codecs
  61. f = codecs.open(name, mode, encoding)
  62. else:
  63. f = open(name, mode)
  64. if 'w' in mode:
  65. os.chmod(name, 0600)
  66. return f
  67. def option_dict(options):
  68. """ Return a dictionary mapping option names to Option instances.
  69. """
  70. d = {}
  71. for option in options:
  72. d[option.name] = option
  73. return d
  74. # Alias
  75. getpasswd = invisible_input
  76. _integerRE = re.compile('\s*(-?\d+)\s*$')
  77. _integerRangeRE = re.compile('\s*(-?\d+)\s*-\s*(-?\d+)\s*$')
  78. def srange(s,
  79. split=string.split,integer=_integerRE,
  80. integerRange=_integerRangeRE):
  81. """ Converts a textual representation of integer numbers and ranges
  82. to a Python list.
  83. Supported formats: 2,3,4,2-10,-1 - -3, 5 - -2
  84. Values are appended to the created list in the order specified
  85. in the string.
  86. """
  87. l = []
  88. append = l.append
  89. for entry in split(s,','):
  90. m = integer.match(entry)
  91. if m:
  92. append(int(m.groups()[0]))
  93. continue
  94. m = integerRange.match(entry)
  95. if m:
  96. start,end = map(int,m.groups())
  97. l[len(l):] = range(start,end+1)
  98. return l
  99. def abspath(path,
  100. expandvars=os.path.expandvars,expanduser=os.path.expanduser,
  101. join=os.path.join,getcwd=os.getcwd):
  102. """ Return the corresponding absolute path for path.
  103. path is expanded in the usual shell ways before
  104. joining it with the current working directory.
  105. """
  106. try:
  107. path = expandvars(path)
  108. except AttributeError:
  109. pass
  110. try:
  111. path = expanduser(path)
  112. except AttributeError:
  113. pass
  114. return join(getcwd(), path)
  115. ### Option classes
  116. class Option:
  117. """ Option base class. Takes no argument.
  118. """
  119. default = None
  120. helptext = ''
  121. prefix = '-'
  122. takes_argument = 0
  123. has_default = 0
  124. tab = 15
  125. def __init__(self,name,help=None):
  126. if not name[:1] == '-':
  127. raise TypeError,'option names must start with "-"'
  128. if name[1:2] == '-':
  129. self.prefix = '--'
  130. self.name = name[2:]
  131. else:
  132. self.name = name[1:]
  133. if help:
  134. self.help = help
  135. def __str__(self):
  136. o = self
  137. name = o.prefix + o.name
  138. if o.takes_argument:
  139. name = name + ' arg'
  140. if len(name) > self.tab:
  141. name = name + '\n' + ' ' * (self.tab + 1 + len(o.prefix))
  142. else:
  143. name = '%-*s ' % (self.tab, name)
  144. description = o.help
  145. if o.has_default:
  146. description = description + ' (%s)' % o.default
  147. return '%s %s' % (name, description)
  148. class ArgumentOption(Option):
  149. """ Option that takes an argument.
  150. An optional default argument can be given.
  151. """
  152. def __init__(self,name,help=None,default=None):
  153. # Basemethod
  154. Option.__init__(self,name,help)
  155. if default is not None:
  156. self.default = default
  157. self.has_default = 1
  158. self.takes_argument = 1
  159. class SwitchOption(Option):
  160. """ Options that can be on or off. Has an optional default value.
  161. """
  162. def __init__(self,name,help=None,default=None):
  163. # Basemethod
  164. Option.__init__(self,name,help)
  165. if default is not None:
  166. self.default = default
  167. self.has_default = 1
  168. ### Application baseclass
  169. class Application:
  170. """ Command line application interface with builtin argument
  171. parsing.
  172. """
  173. # Options the program accepts (Option instances)
  174. options = []
  175. # Standard settings; these are appended to options in __init__
  176. preset_options = [SwitchOption('-v',
  177. 'generate verbose output'),
  178. SwitchOption('-h',
  179. 'show this help text'),
  180. SwitchOption('--help',
  181. 'show this help text'),
  182. SwitchOption('--debug',
  183. 'enable debugging'),
  184. SwitchOption('--copyright',
  185. 'show copyright'),
  186. SwitchOption('--examples',
  187. 'show examples of usage')]
  188. # The help layout looks like this:
  189. # [header] - defaults to ''
  190. #
  191. # [synopsis] - formatted as '<self.name> %s' % self.synopsis
  192. #
  193. # options:
  194. # [options] - formatted from self.options
  195. #
  196. # [version] - formatted as 'Version:\n %s' % self.version, if given
  197. #
  198. # [about] - defaults to ''
  199. #
  200. # Note: all fields that do not behave as template are formatted
  201. # using the instances dictionary as substitution namespace,
  202. # e.g. %(name)s will be replaced by the applications name.
  203. #
  204. # Header (default to program name)
  205. header = ''
  206. # Name (defaults to program name)
  207. name = ''
  208. # Synopsis (%(name)s is replaced by the program name)
  209. synopsis = '%(name)s [option] files...'
  210. # Version (optional)
  211. version = ''
  212. # General information printed after the possible options (optional)
  213. about = ''
  214. # Examples of usage to show when the --examples option is given (optional)
  215. examples = ''
  216. # Copyright to show
  217. copyright = __copyright__
  218. # Apply file globbing ?
  219. globbing = 1
  220. # Generate debug output ?
  221. debug = 0
  222. # Generate verbose output ?
  223. verbose = 0
  224. # Internal errors to catch
  225. InternalError = exceptions.Exception
  226. # Instance variables:
  227. values = None # Dictionary of passed options (or default values)
  228. # indexed by the options name, e.g. '-h'
  229. files = None # List of passed filenames
  230. optionlist = None # List of passed options
  231. def __init__(self,argv=None):
  232. # Setup application specs
  233. if argv is None:
  234. argv = sys.argv
  235. self.filename = os.path.split(argv[0])[1]
  236. if not self.name:
  237. self.name = os.path.split(self.filename)[1]
  238. else:
  239. self.name = self.name
  240. if not self.header:
  241. self.header = self.name
  242. else:
  243. self.header = self.header
  244. # Init .arguments list
  245. self.arguments = argv[1:]
  246. # Setup Option mapping
  247. self.option_map = option_dict(self.options)
  248. # Append preset options
  249. for option in self.preset_options:
  250. if not self.option_map.has_key(option.name):
  251. self.add_option(option)
  252. # Init .files list
  253. self.files = []
  254. # Start Application
  255. try:
  256. # Process startup
  257. rc = self.startup()
  258. if rc is not None:
  259. raise SystemExit,rc
  260. # Parse command line
  261. rc = self.parse()
  262. if rc is not None:
  263. raise SystemExit,rc
  264. # Start application
  265. rc = self.main()
  266. if rc is None:
  267. rc = 0
  268. except SystemExit,rc:
  269. pass
  270. except KeyboardInterrupt:
  271. print
  272. print '* User Break'
  273. print
  274. rc = 1
  275. except self.InternalError:
  276. print
  277. print '* Internal Error (use --debug to display the traceback)'
  278. if self.debug:
  279. print
  280. traceback.print_exc(20, sys.stdout)
  281. elif self.verbose:
  282. print ' %s: %s' % sys.exc_info()[:2]
  283. print
  284. rc = 1
  285. raise SystemExit,rc
  286. def add_option(self, option):
  287. """ Add a new Option instance to the Application dynamically.
  288. Note that this has to be done *before* .parse() is being
  289. executed.
  290. """
  291. self.options.append(option)
  292. self.option_map[option.name] = option
  293. def startup(self):
  294. """ Set user defined instance variables.
  295. If this method returns anything other than None, the
  296. process is terminated with the return value as exit code.
  297. """
  298. return None
  299. def exit(self, rc=0):
  300. """ Exit the program.
  301. rc is used as exit code and passed back to the calling
  302. program. It defaults to 0 which usually means: OK.
  303. """
  304. raise SystemExit, rc
  305. def parse(self):
  306. """ Parse the command line and fill in self.values and self.files.
  307. After having parsed the options, the remaining command line
  308. arguments are interpreted as files and passed to .handle_files()
  309. for processing.
  310. As final step the option handlers are called in the order
  311. of the options given on the command line.
  312. """
  313. # Parse arguments
  314. self.values = values = {}
  315. for o in self.options:
  316. if o.has_default:
  317. values[o.prefix+o.name] = o.default
  318. else:
  319. values[o.prefix+o.name] = 0
  320. flags,lflags = _getopt_flags(self.options)
  321. try:
  322. optlist,files = getopt.getopt(self.arguments,flags,lflags)
  323. if self.globbing:
  324. l = []
  325. for f in files:
  326. gf = glob.glob(f)
  327. if not gf:
  328. l.append(f)
  329. else:
  330. l[len(l):] = gf
  331. files = l
  332. self.optionlist = optlist
  333. self.files = files + self.files
  334. except getopt.error,why:
  335. self.help(why)
  336. sys.exit(1)
  337. # Call file handler
  338. rc = self.handle_files(self.files)
  339. if rc is not None:
  340. sys.exit(rc)
  341. # Call option handlers
  342. for optionname, value in optlist:
  343. # Try to convert value to integer
  344. try:
  345. value = string.atoi(value)
  346. except ValueError:
  347. pass
  348. # Find handler and call it (or count the number of option
  349. # instances on the command line)
  350. handlername = 'handle' + string.replace(optionname, '-', '_')
  351. try:
  352. handler = getattr(self, handlername)
  353. except AttributeError:
  354. if value == '':
  355. # count the number of occurances
  356. if values.has_key(optionname):
  357. values[optionname] = values[optionname] + 1
  358. else:
  359. values[optionname] = 1
  360. else:
  361. values[optionname] = value
  362. else:
  363. rc = handler(value)
  364. if rc is not None:
  365. raise SystemExit, rc
  366. # Apply final file check (for backward compatibility)
  367. rc = self.check_files(self.files)
  368. if rc is not None:
  369. sys.exit(rc)
  370. def check_files(self,filelist):
  371. """ Apply some user defined checks on the files given in filelist.
  372. This may modify filelist in place. A typical application
  373. is checking that at least n files are given.
  374. If this method returns anything other than None, the
  375. process is terminated with the return value as exit code.
  376. """
  377. return None
  378. def help(self,note=''):
  379. self.print_header()
  380. if self.synopsis:
  381. print 'Synopsis:'
  382. # To remain backward compatible:
  383. try:
  384. synopsis = self.synopsis % self.name
  385. except (NameError, KeyError, TypeError):
  386. synopsis = self.synopsis % self.__dict__
  387. print ' ' + synopsis
  388. print
  389. self.print_options()
  390. if self.version:
  391. print 'Version:'
  392. print ' %s' % self.version
  393. print
  394. if self.about:
  395. print string.strip(self.about % self.__dict__)
  396. print
  397. if note:
  398. print '-'*72
  399. print 'Note:',note
  400. print
  401. def notice(self,note):
  402. print '-'*72
  403. print 'Note:',note
  404. print '-'*72
  405. print
  406. def print_header(self):
  407. print '-'*72
  408. print self.header % self.__dict__
  409. print '-'*72
  410. print
  411. def print_options(self):
  412. options = self.options
  413. print 'Options and default settings:'
  414. if not options:
  415. print ' None'
  416. return
  417. long = filter(lambda x: x.prefix == '--', options)
  418. short = filter(lambda x: x.prefix == '-', options)
  419. items = short + long
  420. for o in options:
  421. print ' ',o
  422. print
  423. #
  424. # Example handlers:
  425. #
  426. # If a handler returns anything other than None, processing stops
  427. # and the return value is passed to sys.exit() as argument.
  428. #
  429. # File handler
  430. def handle_files(self,files):
  431. """ This may process the files list in place.
  432. """
  433. return None
  434. # Short option handler
  435. def handle_h(self,arg):
  436. self.help()
  437. return 0
  438. def handle_v(self, value):
  439. """ Turn on verbose output.
  440. """
  441. self.verbose = 1
  442. # Handlers for long options have two underscores in their name
  443. def handle__help(self,arg):
  444. self.help()
  445. return 0
  446. def handle__debug(self,arg):
  447. self.debug = 1
  448. # We don't want to catch internal errors:
  449. self.InternalError = None
  450. def handle__copyright(self,arg):
  451. self.print_header()
  452. print string.strip(self.copyright % self.__dict__)
  453. print
  454. return 0
  455. def handle__examples(self,arg):
  456. self.print_header()
  457. if self.examples:
  458. print 'Examples:'
  459. print
  460. print string.strip(self.examples % self.__dict__)
  461. print
  462. else:
  463. print 'No examples available.'
  464. print
  465. return 0
  466. def main(self):
  467. """ Override this method as program entry point.
  468. The return value is passed to sys.exit() as argument. If
  469. it is None, 0 is assumed (meaning OK). Unhandled
  470. exceptions are reported with exit status code 1 (see
  471. __init__ for further details).
  472. """
  473. return None
  474. # Alias
  475. CommandLine = Application
  476. def _test():
  477. class MyApplication(Application):
  478. header = 'Test Application'
  479. version = __version__
  480. options = [Option('-v','verbose')]
  481. def handle_v(self,arg):
  482. print 'VERBOSE, Yeah !'
  483. cmd = MyApplication()
  484. if not cmd.values['-h']:
  485. cmd.help()
  486. print 'files:',cmd.files
  487. print 'Bye...'
  488. if __name__ == '__main__':
  489. _test()