blob: bcc3c218e30095c02880fb9b5f86d1dcdb5e2887 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""Main command line parser. Implements the pysetup script."""
2
3import os
4import re
5import sys
6import getopt
7import logging
8
9from packaging import logger
10from packaging.dist import Distribution
Tarek Ziade721ccd02011-06-02 12:00:44 +020011from packaging.util import _is_archive_file, generate_setup_py
Tarek Ziade1231a4e2011-05-19 13:07:25 +020012from packaging.command import get_command_class, STANDARD_COMMANDS
13from packaging.install import install, install_local_project, remove
14from packaging.database import get_distribution, get_distributions
15from packaging.depgraph import generate_graph
16from packaging.fancy_getopt import FancyGetopt
17from packaging.errors import (PackagingArgError, PackagingError,
18 PackagingModuleError, PackagingClassError,
19 CCompilerError)
20
21
22command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
23
24common_usage = """\
25Actions:
26%(actions)s
27
28To get more help on an action, use:
29
30 pysetup action --help
31"""
32
33create_usage = """\
34Usage: pysetup create
35 or: pysetup create --help
36
Éric Araujo18efecf2011-06-04 22:33:59 +020037Create a new Python project.
Tarek Ziade1231a4e2011-05-19 13:07:25 +020038"""
39
Tarek Ziade721ccd02011-06-02 12:00:44 +020040generate_usage = """\
41Usage: pysetup generate-setup
42 or: pysetup generate-setup --help
43
Éric Araujo18efecf2011-06-04 22:33:59 +020044Generate a setup.py script for backward-compatibility purposes.
Tarek Ziade721ccd02011-06-02 12:00:44 +020045"""
46
47
Tarek Ziade1231a4e2011-05-19 13:07:25 +020048graph_usage = """\
49Usage: pysetup graph dist
50 or: pysetup graph --help
51
52Print dependency graph for the distribution.
53
54positional arguments:
55 dist installed distribution name
56"""
57
58install_usage = """\
59Usage: pysetup install [dist]
60 or: pysetup install [archive]
61 or: pysetup install [src_dir]
62 or: pysetup install --help
63
64Install a Python distribution from the indexes, source directory, or sdist.
65
66positional arguments:
67 archive path to source distribution (zip, tar.gz)
68 dist distribution name to install from the indexes
69 scr_dir path to source directory
70
71"""
72
73metadata_usage = """\
74Usage: pysetup metadata [dist] [-f field ...]
75 or: pysetup metadata [dist] [--all]
76 or: pysetup metadata --help
77
78Print metadata for the distribution.
79
80positional arguments:
81 dist installed distribution name
82
83optional arguments:
84 -f metadata field to print
85 --all print all metadata fields
86"""
87
88remove_usage = """\
89Usage: pysetup remove dist [-y]
90 or: pysetup remove --help
91
92Uninstall a Python distribution.
93
94positional arguments:
95 dist installed distribution name
96
97optional arguments:
Éric Araujo18efecf2011-06-04 22:33:59 +020098 -y auto confirm distribution removal
Tarek Ziade1231a4e2011-05-19 13:07:25 +020099"""
100
101run_usage = """\
102Usage: pysetup run [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
103 or: pysetup run --help
104 or: pysetup run --list-commands
105 or: pysetup run cmd --help
106"""
107
108list_usage = """\
109Usage: pysetup list dist [dist ...]
110 or: pysetup list --help
111 or: pysetup list --all
112
113Print name, version and location for the matching installed distributions.
114
115positional arguments:
116 dist installed distribution name
117
118optional arguments:
119 --all list all installed distributions
120"""
121
122search_usage = """\
123Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
124 or: pysetup search --help
125
126Search the indexes for the matching projects.
127
128positional arguments:
129 project the project pattern to search for
130
131optional arguments:
132 --xmlrpc [url] wether to use the xmlrpc index or not. If an url is
133 specified, it will be used rather than the default one.
134
135 --simple [url] wether to use the simple index or not. If an url is
136 specified, it will be used rather than the default one.
137
138 --fieldname value Make a search on this field. Can only be used if
139 --xmlrpc has been selected or is the default index.
140
141 --operator or|and Defines what is the operator to use when doing xmlrpc
142 searchs with multiple fieldnames. Can only be used if
143 --xmlrpc has been selected or is the default index.
144"""
145
146global_options = [
147 # The fourth entry for verbose means that it can be repeated.
148 ('verbose', 'v', "run verbosely (default)", True),
149 ('quiet', 'q', "run quietly (turns verbosity off)"),
150 ('dry-run', 'n', "don't actually do anything"),
151 ('help', 'h', "show detailed help message"),
152 ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
153 ('version', None, 'Display the version'),
154]
155
156negative_opt = {'quiet': 'verbose'}
157
158display_options = [
159 ('help-commands', None, "list all available commands"),
160]
161
162display_option_names = [x[0].replace('-', '_') for x in display_options]
163
164
165def _parse_args(args, options, long_options):
166 """Transform sys.argv input into a dict.
167
168 :param args: the args to parse (i.e sys.argv)
169 :param options: the list of options to pass to getopt
170 :param long_options: the list of string with the names of the long options
171 to be passed to getopt.
172
173 The function returns a dict with options/long_options as keys and matching
174 values as values.
175 """
176 optlist, args = getopt.gnu_getopt(args, options, long_options)
177 optdict = {}
178 optdict['args'] = args
179 for k, v in optlist:
180 k = k.lstrip('-')
181 if k not in optdict:
182 optdict[k] = []
183 if v:
184 optdict[k].append(v)
185 else:
186 optdict[k].append(v)
187 return optdict
188
189
190class action_help:
191 """Prints a help message when the standard help flags: -h and --help
192 are used on the commandline.
193 """
194
195 def __init__(self, help_msg):
196 self.help_msg = help_msg
197
198 def __call__(self, f):
199 def wrapper(*args, **kwargs):
200 f_args = args[1]
201 if '--help' in f_args or '-h' in f_args:
202 print(self.help_msg)
203 return
204 return f(*args, **kwargs)
205 return wrapper
206
207
208@action_help(create_usage)
209def _create(distpatcher, args, **kw):
210 from packaging.create import main
211 return main()
212
213
Tarek Ziade721ccd02011-06-02 12:00:44 +0200214@action_help(generate_usage)
215def _generate(distpatcher, args, **kw):
216 generate_setup_py()
217 print('The setup.py was generated')
218
219
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200220@action_help(graph_usage)
221def _graph(dispatcher, args, **kw):
222 name = args[1]
223 dist = get_distribution(name, use_egg_info=True)
224 if dist is None:
225 print('Distribution not found.')
226 else:
227 dists = get_distributions(use_egg_info=True)
228 graph = generate_graph(dists)
229 print(graph.repr_node(dist))
230
231
232@action_help(install_usage)
233def _install(dispatcher, args, **kw):
234 # first check if we are in a source directory
235 if len(args) < 2:
236 # are we inside a project dir?
237 listing = os.listdir(os.getcwd())
238 if 'setup.py' in listing or 'setup.cfg' in listing:
239 args.insert(1, os.getcwd())
240 else:
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200241 logger.warning('No project to install.')
242 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200243
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200244 target = args[1]
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200245 # installing from a source dir or archive file?
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200246 if os.path.isdir(target) or _is_archive_file(target):
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200247 if install_local_project(target):
248 return 0
249 else:
250 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200251 else:
252 # download from PyPI
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200253 if install(target):
254 return 0
255 else:
256 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200257
258
259@action_help(metadata_usage)
260def _metadata(dispatcher, args, **kw):
261 opts = _parse_args(args[1:], 'f:', ['all'])
262 if opts['args']:
263 name = opts['args'][0]
264 dist = get_distribution(name, use_egg_info=True)
265 if dist is None:
266 logger.warning('%s not installed', name)
267 return
268 else:
269 logger.info('searching local dir for metadata')
270 dist = Distribution()
271 dist.parse_config_files()
272
273 metadata = dist.metadata
274
275 if 'all' in opts:
276 keys = metadata.keys()
277 else:
278 if 'f' in opts:
279 keys = (k for k in opts['f'] if k in metadata)
280 else:
281 keys = ()
282
283 for key in keys:
284 if key in metadata:
285 print(metadata._convert_name(key) + ':')
286 value = metadata[key]
287 if isinstance(value, list):
288 for v in value:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200289 print(' ', v)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200290 else:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200291 print(' ', value.replace('\n', '\n '))
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200292
293
294@action_help(remove_usage)
295def _remove(distpatcher, args, **kw):
296 opts = _parse_args(args[1:], 'y', [])
297 if 'y' in opts:
298 auto_confirm = True
299 else:
300 auto_confirm = False
301
302 for dist in set(opts['args']):
303 try:
304 remove(dist, auto_confirm=auto_confirm)
305 except PackagingError:
306 logger.warning('%s not installed', dist)
307
308
309@action_help(run_usage)
310def _run(dispatcher, args, **kw):
311 parser = dispatcher.parser
312 args = args[1:]
313
314 commands = STANDARD_COMMANDS # + extra commands
315
316 if args == ['--list-commands']:
317 print('List of available commands:')
318 cmds = sorted(commands)
319
320 for cmd in cmds:
321 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
322 desc = getattr(cls, 'description',
323 '(no description available)')
324 print(' %s: %s' % (cmd, desc))
325 return
326
327 while args:
328 args = dispatcher._parse_command_opts(parser, args)
329 if args is None:
330 return
331
332 # create the Distribution class
333 # need to feed setup.cfg here !
334 dist = Distribution()
335
336 # Find and parse the config file(s): they will override options from
337 # the setup script, but be overridden by the command line.
338
339 # XXX still need to be extracted from Distribution
340 dist.parse_config_files()
341
342 try:
343 for cmd in dispatcher.commands:
344 dist.run_command(cmd, dispatcher.command_options[cmd])
345
346 except KeyboardInterrupt:
347 raise SystemExit("interrupted")
348 except (IOError, os.error, PackagingError, CCompilerError) as msg:
349 raise SystemExit("error: " + str(msg))
350
351 # XXX this is crappy
352 return dist
353
354
355@action_help(list_usage)
356def _list(dispatcher, args, **kw):
357 opts = _parse_args(args[1:], '', ['all'])
358 dists = get_distributions(use_egg_info=True)
Tarek Ziade441531f2011-05-31 09:18:24 +0200359 if 'all' in opts or opts['args'] == []:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200360 results = dists
Éric Araujo73c175f2011-07-29 02:20:39 +0200361 listall = True
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200362 else:
363 results = [d for d in dists if d.name.lower() in opts['args']]
Éric Araujo73c175f2011-07-29 02:20:39 +0200364 listall = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200365
Tarek Ziade441531f2011-05-31 09:18:24 +0200366 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200367 for dist in results:
368 print('%s %s at %s' % (dist.name, dist.metadata['version'], dist.path))
Tarek Ziadee2655972011-05-31 12:15:42 +0200369 number += 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200370
Éric Araujo3cab2f12011-06-08 04:10:57 +0200371 print()
Tarek Ziade441531f2011-05-31 09:18:24 +0200372 if number == 0:
Éric Araujo73c175f2011-07-29 02:20:39 +0200373 if listall:
374 print('Nothing seems to be installed.')
375 else:
376 print('No matching distribution found.')
377 return 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200378 else:
379 print('Found %d projects installed.' % number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200380
381
382@action_help(search_usage)
383def _search(dispatcher, args, **kw):
384 """The search action.
385
386 It is able to search for a specific index (specified with --index), using
387 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
388 """
Tarek Ziadee2655972011-05-31 12:15:42 +0200389 #opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200390 # 1. what kind of index is requested ? (xmlrpc / simple)
Éric Araujo2ef747c2011-06-04 22:33:16 +0200391 raise NotImplementedError
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200392
393
394actions = [
395 ('run', 'Run one or several commands', _run),
396 ('metadata', 'Display the metadata of a project', _metadata),
397 ('install', 'Install a project', _install),
398 ('remove', 'Remove a project', _remove),
399 ('search', 'Search for a project in the indexes', _search),
Éric Araujo18efecf2011-06-04 22:33:59 +0200400 ('list', 'List installed releases', _list),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200401 ('graph', 'Display a graph', _graph),
Éric Araujo18efecf2011-06-04 22:33:59 +0200402 ('create', 'Create a project', _create),
403 ('generate-setup', 'Generate a backward-comptatible setup.py', _generate),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200404]
405
406
407class Dispatcher:
408 """Reads the command-line options
409 """
410 def __init__(self, args=None):
411 self.verbose = 1
412 self.dry_run = False
413 self.help = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200414 self.cmdclass = {}
415 self.commands = []
416 self.command_options = {}
417
418 for attr in display_option_names:
419 setattr(self, attr, False)
420
421 self.parser = FancyGetopt(global_options + display_options)
422 self.parser.set_negative_aliases(negative_opt)
423 # FIXME this parses everything, including command options (e.g. "run
424 # build -i" errors with "option -i not recognized")
425 args = self.parser.getopt(args=args, object=self)
426
427 # if first arg is "run", we have some commands
428 if len(args) == 0:
429 self.action = None
430 else:
431 self.action = args[0]
432
433 allowed = [action[0] for action in actions] + [None]
434 if self.action not in allowed:
435 msg = 'Unrecognized action "%s"' % self.action
436 raise PackagingArgError(msg)
437
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200438 self._set_logger()
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200439 self.args = args
440
Tarek Ziadee2655972011-05-31 12:15:42 +0200441 # for display options we return immediately
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200442 if self.help or self.action is None:
443 self._show_help(self.parser, display_options_=False)
444
445 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200446 # setting up the logging level from the command-line options
447 # -q gets warning, error and critical
448 if self.verbose == 0:
449 level = logging.WARNING
450 # default level or -v gets info too
451 # XXX there's a bug somewhere: the help text says that -v is default
452 # (and verbose is set to 1 above), but when the user explicitly gives
453 # -v on the command line, self.verbose is incremented to 2! Here we
454 # compensate for that (I tested manually). On a related note, I think
455 # it's a good thing to use -q/nothing/-v/-vv on the command line
456 # instead of logging constants; it will be easy to add support for
457 # logging configuration in setup.cfg for advanced users. --merwok
458 elif self.verbose in (1, 2):
459 level = logging.INFO
460 else: # -vv and more for debug
461 level = logging.DEBUG
462
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200463 # setting up the stream handler
464 handler = logging.StreamHandler(sys.stderr)
465 handler.setLevel(level)
466 logger.addHandler(handler)
467 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200468
469 def _parse_command_opts(self, parser, args):
470 # Pull the current command from the head of the command line
471 command = args[0]
472 if not command_re.match(command):
473 raise SystemExit("invalid command name %r" % (command,))
474 self.commands.append(command)
475
476 # Dig up the command class that implements this command, so we
477 # 1) know that it's a valid command, and 2) know which options
478 # it takes.
479 try:
480 cmd_class = get_command_class(command)
481 except PackagingModuleError as msg:
482 raise PackagingArgError(msg)
483
484 # XXX We want to push this in packaging.command
485 #
486 # Require that the command class be derived from Command -- want
487 # to be sure that the basic "command" interface is implemented.
488 for meth in ('initialize_options', 'finalize_options', 'run'):
489 if hasattr(cmd_class, meth):
490 continue
491 raise PackagingClassError(
492 'command %r must implement %r' % (cmd_class, meth))
493
494 # Also make sure that the command object provides a list of its
495 # known options.
496 if not (hasattr(cmd_class, 'user_options') and
497 isinstance(cmd_class.user_options, list)):
498 raise PackagingClassError(
499 "command class %s must provide "
500 "'user_options' attribute (a list of tuples)" % cmd_class)
501
502 # If the command class has a list of negative alias options,
503 # merge it in with the global negative aliases.
504 _negative_opt = negative_opt.copy()
505
506 if hasattr(cmd_class, 'negative_opt'):
507 _negative_opt.update(cmd_class.negative_opt)
508
509 # Check for help_options in command class. They have a different
510 # format (tuple of four) so we need to preprocess them here.
511 if (hasattr(cmd_class, 'help_options') and
512 isinstance(cmd_class.help_options, list)):
513 help_options = cmd_class.help_options[:]
514 else:
515 help_options = []
516
517 # All commands support the global options too, just by adding
518 # in 'global_options'.
519 parser.set_option_table(global_options +
520 cmd_class.user_options +
521 help_options)
522 parser.set_negative_aliases(_negative_opt)
523 args, opts = parser.getopt(args[1:])
524
525 if hasattr(opts, 'help') and opts.help:
526 self._show_command_help(cmd_class)
527 return
528
529 if (hasattr(cmd_class, 'help_options') and
530 isinstance(cmd_class.help_options, list)):
531 help_option_found = False
532 for help_option, short, desc, func in cmd_class.help_options:
533 if hasattr(opts, help_option.replace('-', '_')):
534 help_option_found = True
535 if hasattr(func, '__call__'):
536 func()
537 else:
538 raise PackagingClassError(
539 "invalid help function %r for help option %r: "
540 "must be a callable object (function, etc.)"
541 % (func, help_option))
542
543 if help_option_found:
544 return
545
546 # Put the options from the command line into their official
547 # holding pen, the 'command_options' dictionary.
548 opt_dict = self.get_option_dict(command)
549 for name, value in vars(opts).items():
550 opt_dict[name] = ("command line", value)
551
552 return args
553
554 def get_option_dict(self, command):
555 """Get the option dictionary for a given command. If that
556 command's option dictionary hasn't been created yet, then create it
557 and return the new dictionary; otherwise, return the existing
558 option dictionary.
559 """
560 d = self.command_options.get(command)
561 if d is None:
562 d = self.command_options[command] = {}
563 return d
564
565 def show_help(self):
566 self._show_help(self.parser)
567
568 def print_usage(self, parser):
569 parser.set_option_table(global_options)
570
571 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
572 usage = common_usage % {'actions': '\n'.join(actions_)}
573
574 parser.print_help(usage + "\nGlobal options:")
575
576 def _show_help(self, parser, global_options_=True, display_options_=True,
577 commands=[]):
578 # late import because of mutual dependence between these modules
579 from packaging.command.cmd import Command
580
581 print('Usage: pysetup [options] action [action_options]')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200582 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200583 if global_options_:
584 self.print_usage(self.parser)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200585 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200586
587 if display_options_:
588 parser.set_option_table(display_options)
589 parser.print_help(
590 "Information display options (just display " +
591 "information, ignore any commands)")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200592 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200593
594 for command in commands:
595 if isinstance(command, type) and issubclass(command, Command):
596 cls = command
597 else:
598 cls = get_command_class(command)
599 if (hasattr(cls, 'help_options') and
600 isinstance(cls.help_options, list)):
601 parser.set_option_table(cls.user_options + cls.help_options)
602 else:
603 parser.set_option_table(cls.user_options)
604
605 parser.print_help("Options for %r command:" % cls.__name__)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200606 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200607
608 def _show_command_help(self, command):
609 if isinstance(command, str):
610 command = get_command_class(command)
611
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200612 desc = getattr(command, 'description', '(no description available)')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200613 print('Description:', desc)
614 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200615
616 if (hasattr(command, 'help_options') and
617 isinstance(command.help_options, list)):
618 self.parser.set_option_table(command.user_options +
619 command.help_options)
620 else:
621 self.parser.set_option_table(command.user_options)
622
623 self.parser.print_help("Options:")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200624 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200625
626 def _get_command_groups(self):
627 """Helper function to retrieve all the command class names divided
628 into standard commands (listed in
629 packaging.command.STANDARD_COMMANDS) and extra commands (given in
630 self.cmdclass and not standard commands).
631 """
632 extra_commands = [cmd for cmd in self.cmdclass
633 if cmd not in STANDARD_COMMANDS]
634 return STANDARD_COMMANDS, extra_commands
635
636 def print_commands(self):
637 """Print out a help message listing all available commands with a
638 description of each. The list is divided into standard commands
639 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
640 (given in self.cmdclass and not standard commands). The
641 descriptions come from the command class attribute
642 'description'.
643 """
644 std_commands, extra_commands = self._get_command_groups()
645 max_length = max(len(command)
646 for commands in (std_commands, extra_commands)
647 for command in commands)
648
649 self.print_command_list(std_commands, "Standard commands", max_length)
650 if extra_commands:
651 print()
652 self.print_command_list(extra_commands, "Extra commands",
653 max_length)
654
655 def print_command_list(self, commands, header, max_length):
656 """Print a subset of the list of all commands -- used by
657 'print_commands()'.
658 """
659 print(header + ":")
660
661 for cmd in commands:
662 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
663 description = getattr(cls, 'description',
664 '(no description available)')
665
666 print(" %-*s %s" % (max_length, cmd, description))
667
668 def __call__(self):
669 if self.action is None:
670 return
671 for action, desc, func in actions:
672 if action == self.action:
673 return func(self, self.args)
674 return -1
675
676
677def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200678 old_level = logger.level
Éric Araujo088025f2011-06-04 18:45:40 +0200679 old_handlers = list(logger.handlers)
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200680 try:
681 dispatcher = Dispatcher(args)
682 if dispatcher.action is None:
683 return
684 return dispatcher()
685 finally:
686 logger.setLevel(old_level)
687 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200688
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200689
690if __name__ == '__main__':
691 sys.exit(main())