• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 The Abseil Authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Generic entry point for Abseil Python applications.
16
17To use this module, define a ``main`` function with a single ``argv`` argument
18and call ``app.run(main)``. For example::
19
20    def main(argv):
21      if len(argv) > 1:
22        raise app.UsageError('Too many command-line arguments.')
23
24    if __name__ == '__main__':
25      app.run(main)
26"""
27
28import collections
29import errno
30import os
31import pdb
32import sys
33import textwrap
34import traceback
35
36from absl import command_name
37from absl import flags
38from absl import logging
39
40try:
41  import faulthandler
42except ImportError:
43  faulthandler = None
44
45FLAGS = flags.FLAGS
46
47flags.DEFINE_boolean('run_with_pdb', False, 'Set to true for PDB debug mode')
48flags.DEFINE_boolean('pdb_post_mortem', False,
49                     'Set to true to handle uncaught exceptions with PDB '
50                     'post mortem.')
51flags.DEFINE_alias('pdb', 'pdb_post_mortem')
52flags.DEFINE_boolean('run_with_profiling', False,
53                     'Set to true for profiling the script. '
54                     'Execution will be slower, and the output format might '
55                     'change over time.')
56flags.DEFINE_string('profile_file', None,
57                    'Dump profile information to a file (for python -m '
58                    'pstats). Implies --run_with_profiling.')
59flags.DEFINE_boolean('use_cprofile_for_profiling', True,
60                     'Use cProfile instead of the profile module for '
61                     'profiling. This has no effect unless '
62                     '--run_with_profiling is set.')
63flags.DEFINE_boolean('only_check_args', False,
64                     'Set to true to validate args and exit.',
65                     allow_hide_cpp=True)
66
67
68# If main() exits via an abnormal exception, call into these
69# handlers before exiting.
70EXCEPTION_HANDLERS = []
71
72
73class Error(Exception):
74  pass
75
76
77class UsageError(Error):
78  """Exception raised when the arguments supplied by the user are invalid.
79
80  Raise this when the arguments supplied are invalid from the point of
81  view of the application. For example when two mutually exclusive
82  flags have been supplied or when there are not enough non-flag
83  arguments. It is distinct from flags.Error which covers the lower
84  level of parsing and validating individual flags.
85  """
86
87  def __init__(self, message, exitcode=1):
88    super(UsageError, self).__init__(message)
89    self.exitcode = exitcode
90
91
92class HelpFlag(flags.BooleanFlag):
93  """Special boolean flag that displays usage and raises SystemExit."""
94  NAME = 'help'
95  SHORT_NAME = '?'
96
97  def __init__(self):
98    super(HelpFlag, self).__init__(
99        self.NAME, False, 'show this help',
100        short_name=self.SHORT_NAME, allow_hide_cpp=True)
101
102  def parse(self, arg):
103    if self._parse(arg):
104      usage(shorthelp=True, writeto_stdout=True)
105      # Advertise --helpfull on stdout, since usage() was on stdout.
106      print()
107      print('Try --helpfull to get a list of all flags.')
108      sys.exit(1)
109
110
111class HelpshortFlag(HelpFlag):
112  """--helpshort is an alias for --help."""
113  NAME = 'helpshort'
114  SHORT_NAME = None
115
116
117class HelpfullFlag(flags.BooleanFlag):
118  """Display help for flags in the main module and all dependent modules."""
119
120  def __init__(self):
121    super(HelpfullFlag, self).__init__(
122        'helpfull', False, 'show full help', allow_hide_cpp=True)
123
124  def parse(self, arg):
125    if self._parse(arg):
126      usage(writeto_stdout=True)
127      sys.exit(1)
128
129
130class HelpXMLFlag(flags.BooleanFlag):
131  """Similar to HelpfullFlag, but generates output in XML format."""
132
133  def __init__(self):
134    super(HelpXMLFlag, self).__init__(
135        'helpxml', False, 'like --helpfull, but generates XML output',
136        allow_hide_cpp=True)
137
138  def parse(self, arg):
139    if self._parse(arg):
140      flags.FLAGS.write_help_in_xml_format(sys.stdout)
141      sys.exit(1)
142
143
144def parse_flags_with_usage(args):
145  """Tries to parse the flags, print usage, and exit if unparsable.
146
147  Args:
148    args: [str], a non-empty list of the command line arguments including
149        program name.
150
151  Returns:
152    [str], a non-empty list of remaining command line arguments after parsing
153    flags, including program name.
154  """
155  try:
156    return FLAGS(args)
157  except flags.Error as error:
158    message = str(error)
159    if '\n' in message:
160      final_message = 'FATAL Flags parsing error:\n%s\n' % textwrap.indent(
161          message, '  ')
162    else:
163      final_message = 'FATAL Flags parsing error: %s\n' % message
164    sys.stderr.write(final_message)
165    sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
166    sys.exit(1)
167
168
169_define_help_flags_called = False
170
171
172def define_help_flags():
173  """Registers help flags. Idempotent."""
174  # Use a global to ensure idempotence.
175  global _define_help_flags_called
176
177  if not _define_help_flags_called:
178    flags.DEFINE_flag(HelpFlag())
179    flags.DEFINE_flag(HelpshortFlag())  # alias for --help
180    flags.DEFINE_flag(HelpfullFlag())
181    flags.DEFINE_flag(HelpXMLFlag())
182    _define_help_flags_called = True
183
184
185def _register_and_parse_flags_with_usage(
186    argv=None,
187    flags_parser=parse_flags_with_usage,
188):
189  """Registers help flags, parses arguments and shows usage if appropriate.
190
191  This also calls sys.exit(0) if flag --only_check_args is True.
192
193  Args:
194    argv: [str], a non-empty list of the command line arguments including
195        program name, sys.argv is used if None.
196    flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
197        The return value of this function is passed to `main` untouched.
198        It must guarantee FLAGS is parsed after this function is called.
199
200  Returns:
201    The return value of `flags_parser`. When using the default `flags_parser`,
202    it returns the following:
203    [str], a non-empty list of remaining command line arguments after parsing
204    flags, including program name.
205
206  Raises:
207    Error: Raised when flags_parser is called, but FLAGS is not parsed.
208    SystemError: Raised when it's called more than once.
209  """
210  if _register_and_parse_flags_with_usage.done:
211    raise SystemError('Flag registration can be done only once.')
212
213  define_help_flags()
214
215  original_argv = sys.argv if argv is None else argv
216  args_to_main = flags_parser(original_argv)
217  if not FLAGS.is_parsed():
218    raise Error('FLAGS must be parsed after flags_parser is called.')
219
220  # Exit when told so.
221  if FLAGS.only_check_args:
222    sys.exit(0)
223  # Immediately after flags are parsed, bump verbosity to INFO if the flag has
224  # not been set.
225  if FLAGS['verbosity'].using_default_value:
226    FLAGS.verbosity = 0
227  _register_and_parse_flags_with_usage.done = True
228
229  return args_to_main
230
231_register_and_parse_flags_with_usage.done = False
232
233
234def _run_main(main, argv):
235  """Calls main, optionally with pdb or profiler."""
236  if FLAGS.run_with_pdb:
237    sys.exit(pdb.runcall(main, argv))
238  elif FLAGS.run_with_profiling or FLAGS.profile_file:
239    # Avoid import overhead since most apps (including performance-sensitive
240    # ones) won't be run with profiling.
241    import atexit
242    if FLAGS.use_cprofile_for_profiling:
243      import cProfile as profile
244    else:
245      import profile
246    profiler = profile.Profile()
247    if FLAGS.profile_file:
248      atexit.register(profiler.dump_stats, FLAGS.profile_file)
249    else:
250      atexit.register(profiler.print_stats)
251    retval = profiler.runcall(main, argv)
252    sys.exit(retval)
253  else:
254    sys.exit(main(argv))
255
256
257def _call_exception_handlers(exception):
258  """Calls any installed exception handlers."""
259  for handler in EXCEPTION_HANDLERS:
260    try:
261      if handler.wants(exception):
262        handler.handle(exception)
263    except:  # pylint: disable=bare-except
264      try:
265        # We don't want to stop for exceptions in the exception handlers but
266        # we shouldn't hide them either.
267        logging.error(traceback.format_exc())
268      except:  # pylint: disable=bare-except
269        # In case even the logging statement fails, ignore.
270        pass
271
272
273def run(
274    main,
275    argv=None,
276    flags_parser=parse_flags_with_usage,
277):
278  """Begins executing the program.
279
280  Args:
281    main: The main function to execute. It takes an single argument "argv",
282        which is a list of command line arguments with parsed flags removed.
283        The return value is passed to `sys.exit`, and so for example
284        a return value of 0 or None results in a successful termination, whereas
285        a return value of 1 results in abnormal termination.
286        For more details, see https://docs.python.org/3/library/sys#sys.exit
287    argv: A non-empty list of the command line arguments including program name,
288        sys.argv is used if None.
289    flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
290        The return value of this function is passed to `main` untouched.
291        It must guarantee FLAGS is parsed after this function is called.
292        Should be passed as a keyword-only arg which will become mandatory in a
293        future release.
294  - Parses command line flags with the flag module.
295  - If there are any errors, prints usage().
296  - Calls main() with the remaining arguments.
297  - If main() raises a UsageError, prints usage and the error message.
298  """
299  try:
300    args = _run_init(
301        sys.argv if argv is None else argv,
302        flags_parser,
303    )
304    while _init_callbacks:
305      callback = _init_callbacks.popleft()
306      callback()
307    try:
308      _run_main(main, args)
309    except UsageError as error:
310      usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)
311    except:
312      exc = sys.exc_info()[1]
313      # Don't try to post-mortem debug successful SystemExits, since those
314      # mean there wasn't actually an error. In particular, the test framework
315      # raises SystemExit(False) even if all tests passed.
316      if isinstance(exc, SystemExit) and not exc.code:
317        raise
318
319      # Check the tty so that we don't hang waiting for input in an
320      # non-interactive scenario.
321      if FLAGS.pdb_post_mortem and sys.stdout.isatty():
322        traceback.print_exc()
323        print()
324        print(' *** Entering post-mortem debugging ***')
325        print()
326        pdb.post_mortem()
327      raise
328  except Exception as e:
329    _call_exception_handlers(e)
330    raise
331
332# Callbacks which have been deferred until after _run_init has been called.
333_init_callbacks = collections.deque()
334
335
336def call_after_init(callback):
337  """Calls the given callback only once ABSL has finished initialization.
338
339  If ABSL has already finished initialization when ``call_after_init`` is
340  called then the callback is executed immediately, otherwise `callback` is
341  stored to be executed after ``app.run`` has finished initializing (aka. just
342  before the main function is called).
343
344  If called after ``app.run``, this is equivalent to calling ``callback()`` in
345  the caller thread. If called before ``app.run``, callbacks are run
346  sequentially (in an undefined order) in the same thread as ``app.run``.
347
348  Args:
349    callback: a callable to be called once ABSL has finished initialization.
350      This may be immediate if initialization has already finished. It
351      takes no arguments and returns nothing.
352  """
353  if _run_init.done:
354    callback()
355  else:
356    _init_callbacks.append(callback)
357
358
359def _run_init(
360    argv,
361    flags_parser,
362):
363  """Does one-time initialization and re-parses flags on rerun."""
364  if _run_init.done:
365    return flags_parser(argv)
366  command_name.make_process_name_useful()
367  # Set up absl logging handler.
368  logging.use_absl_handler()
369  args = _register_and_parse_flags_with_usage(
370      argv=argv,
371      flags_parser=flags_parser,
372  )
373  if faulthandler:
374    try:
375      faulthandler.enable()
376    except Exception:  # pylint: disable=broad-except
377      # Some tests verify stderr output very closely, so don't print anything.
378      # Disabled faulthandler is a low-impact error.
379      pass
380  _run_init.done = True
381  return args
382
383
384_run_init.done = False
385
386
387def usage(shorthelp=False, writeto_stdout=False, detailed_error=None,
388          exitcode=None):
389  """Writes __main__'s docstring to stderr with some help text.
390
391  Args:
392    shorthelp: bool, if True, prints only flags from the main module,
393        rather than all flags.
394    writeto_stdout: bool, if True, writes help message to stdout,
395        rather than to stderr.
396    detailed_error: str, additional detail about why usage info was presented.
397    exitcode: optional integer, if set, exits with this status code after
398        writing help.
399  """
400  if writeto_stdout:
401    stdfile = sys.stdout
402  else:
403    stdfile = sys.stderr
404
405  doc = sys.modules['__main__'].__doc__
406  if not doc:
407    doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
408    doc = flags.text_wrap(doc, indent='       ', firstline_indent='')
409  else:
410    # Replace all '%s' with sys.argv[0], and all '%%' with '%'.
411    num_specifiers = doc.count('%') - 2 * doc.count('%%')
412    try:
413      doc %= (sys.argv[0],) * num_specifiers
414    except (OverflowError, TypeError, ValueError):
415      # Just display the docstring as-is.
416      pass
417  if shorthelp:
418    flag_str = FLAGS.main_module_help()
419  else:
420    flag_str = FLAGS.get_help()
421  try:
422    stdfile.write(doc)
423    if flag_str:
424      stdfile.write('\nflags:\n')
425      stdfile.write(flag_str)
426    stdfile.write('\n')
427    if detailed_error is not None:
428      stdfile.write('\n%s\n' % detailed_error)
429  except IOError as e:
430    # We avoid printing a huge backtrace if we get EPIPE, because
431    # "foo.par --help | less" is a frequent use case.
432    if e.errno != errno.EPIPE:
433      raise
434  if exitcode is not None:
435    sys.exit(exitcode)
436
437
438class ExceptionHandler(object):
439  """Base exception handler from which other may inherit."""
440
441  def wants(self, exc):
442    """Returns whether this handler wants to handle the exception or not.
443
444    This base class returns True for all exceptions by default. Override in
445    subclass if it wants to be more selective.
446
447    Args:
448      exc: Exception, the current exception.
449    """
450    del exc  # Unused.
451    return True
452
453  def handle(self, exc):
454    """Do something with the current exception.
455
456    Args:
457      exc: Exception, the current exception
458
459    This method must be overridden.
460    """
461    raise NotImplementedError()
462
463
464def install_exception_handler(handler):
465  """Installs an exception handler.
466
467  Args:
468    handler: ExceptionHandler, the exception handler to install.
469
470  Raises:
471    TypeError: Raised when the handler was not of the correct type.
472
473  All installed exception handlers will be called if main() exits via
474  an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
475  FlagsError or UsageError.
476  """
477  if not isinstance(handler, ExceptionHandler):
478    raise TypeError('handler of type %s does not inherit from ExceptionHandler'
479                    % type(handler))
480  EXCEPTION_HANDLERS.append(handler)
481