Debian Codegraph @

friendly_traceback/__main__.py

raw symbols SCIP
1 """
2 main.py
3 ---------------
4
5 Sets up the various options when Friendly is invoked from the
6 command line. You can find more details by doing::
7
8 python -m friendly -h
9
10 """
11
12 import argparse
13 import platform
14 import runpy
15 import sys
16 import warnings
17 from importlib import import_module
18 from pathlib import Path
19
20 from . import (
21 __version__,
22 debug_helper,
23 exclude_file_from_traceback,
24 explain_traceback,
25 ft_console,
26 install,
27 set_formatter,
28 )
29 from .ft_gettext import current_lang
30
31 versions = f"Friendly-traceback version {__version__}. [Python version: {platform.python_version()}]\n"
32
33
34 def import_function(dotted_path: str) -> type:
35 """Import a function from a module, given its dotted path.
36
37 This is a utility function currently used when a custom formatter
38 is selected using a command line argument::
39
40 python -m friendly --formatter custom_formatter
41 """
42 # Used by HackInScience.org
43 try:
44 module_path, function_name = dotted_path.rsplit(".", 1)
45 except ValueError as err: # pragma: no cover
46 raise ImportError("%s doesn't look like a module path" % dotted_path) from err
47
48 module = import_module(module_path)
49
50 try:
51 return getattr(module, function_name)
52 except AttributeError as err: # pragma: no cover
53 raise ImportError(
54 'Module "%s" does not define a "%s" function' % (module_path, function_name)
55 ) from err
56
57
58 parser = argparse.ArgumentParser(
59 formatter_class=argparse.RawDescriptionHelpFormatter,
60 description=(
61 """Friendly-traceback makes Python tracebacks easier to understand.
62
63 {versions}
64
65 If no source is given Friendly-traceback will start an interactive console.
66 """.format(
67 versions=versions
68 )
69 ),
70 )
71
72 parser.add_argument(
73 "source",
74 nargs="?",
75 help="""Name of the Python script (path/to/my_program.py)
76 to be run as though it was the main module, so that its
77 __name__ does equal '__main__'.
78 """,
79 )
80
81 parser.add_argument(
82 "args",
83 nargs="*",
84 help="""Optional arguments to give to the script specified by source.
85 """,
86 )
87
88 parser.add_argument(
89 "--lang",
90 default="en",
91 help="""This sets the language used by Friendly-traceback.
92 Usually this is a two-letter code such as 'fr' for French.
93 """,
94 )
95
96 parser.add_argument(
97 "--version",
98 help="""Only displays the current version.
99 """,
100 action="store_true",
101 )
102
103 parser.add_argument(
104 "-f",
105 "--formatter",
106 help="""Specifies an output format ('bw' or 'docs')
107 or a custom formatter function, as a dotted path.
108 By default, the console will use 'bw' if it is available.
109 """,
110 )
111
112 parser.add_argument("--debug", help="""For developer use.""", action="store_true")
113 parser.add_argument("--no_debug", help="""For developer use.""", action="store_true")
114
115 parser.add_argument(
116 "--include",
117 help="""Specifies what content to include by default in the traceback.
118 The defaults are 'friendly_tb' if the friendly-console is going to be shown,
119 otherwise it is 'explain'.
120 """,
121 )
122
123
124 parser.add_argument(
125 "--python_prompt",
126 help="""Specifies that the console prompt must the standard python prompt.""",
127 action="store_true",
128 )
129
130
131 def main() -> None:
132 _ = current_lang.translate
133 args = parser.parse_args()
134 if args.version: # pragma: no cover
135 print(f"\nFriendly-Traceback version {__version__}")
136 sys.exit()
137
138 include = "friendly_tb"
139 if args.include: # pragma: no cover
140 include = args.include
141 elif args.source and not sys.flags.interactive:
142 include = "explain"
143 if args.debug: # pragma: no cover
144 debug_helper.DEBUG = True
145 include = "debug_tb"
146 elif args.no_debug: # pragma: no cover
147 debug_helper.DEBUG = False
148
149 install(lang=args.lang, include=include)
150
151 if args.formatter:
152 formatter = args.formatter # noqa
153 if formatter in ["repl", "docs"]:
154 set_formatter(formatter) # pragma: no cover
155 else:
156 set_formatter(import_function(args.formatter))
157 formatter = "repl" # for the console - should not be needed
158 else:
159 set_formatter("repl")
160 formatter = "repl"
161
162 if sys.flags.interactive:
163 warnings.simplefilter("always")
164
165 console_defaults = {}
166 if args.source is not None:
167 filename = Path(args.source)
168 if not filename.exists(): # pragma: no cover
169 print(
170 "\n",
171 _("The file {filename} does not exist.").format(filename=args.source),
172 )
173 return
174
175 exclude_file_from_traceback(runpy.__file__)
176 sys.argv = [args.source, *args.args]
177 try:
178 module_dict = runpy.run_path(args.source, run_name="__main__")
179 console_defaults.update(module_dict)
180 except Exception: # noqa
181 explain_traceback()
182 if sys.flags.interactive: # pragma: no cover
183 ft_console.start_console(
184 local_vars=console_defaults,
185 formatter=formatter,
186 lang=args.lang,
187 ipython_prompt=not args.python_prompt,
188 )
189
190 else: # pragma: no cover
191 ft_console.start_console(
192 local_vars=console_defaults,
193 formatter=formatter,
194 lang=args.lang,
195 ipython_prompt=not args.python_prompt,
196 )
197
198
199 main()