PageRenderTime 721ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/translator/microbench/pybench/CommandLine.py

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