forked frombpython/bpython
- Notifications
You must be signed in to change notification settings - Fork0
Expand file tree
/
Copy pathargs.py
More file actions
238 lines (207 loc) · 7.73 KB
/
args.py
File metadata and controls
238 lines (207 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
# Copyright (c) 2012-2021 Sebastian Ramacher
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module to handle command line argument parsing, for all front-ends.
"""
importargparse
fromtypingimportTuple
importcurtsies
importcwcwidth
importgreenlet
importimportlib.util
importlogging
importos
importpygments
importrequests
importsys
frompathlibimportPath
from .import__version__,__copyright__
from .configimportdefault_config_path,Config
from .translationsimport_
logger=logging.getLogger(__name__)
classArgumentParserFailed(ValueError):
"""Raised by the RaisingOptionParser for a bogus commandline."""
classRaisingArgumentParser(argparse.ArgumentParser):
deferror(self,msg):
raiseArgumentParserFailed()
defversion_banner(base="bpython")->str:
return_("{} version {} on top of Python {} {}").format(
base,
__version__,
sys.version.split()[0],
sys.executable,
)
defcopyright_banner()->str:
return_("{} See AUTHORS.rst for details.").format(__copyright__)
defparse(args,extras=None,ignore_stdin=False)->Tuple:
"""Receive an argument list - if None, use sys.argv - parse all args and
take appropriate action. Also receive optional extra argument: this should
be a tuple of (title, description, callback)
title: The title for the argument group
description: A full description of the argument group
callback: A callback that adds argument to the argument group
e.g.:
def callback(group):
group.add_argument('-f', action='store_true', dest='f', help='Explode')
group.add_argument('-l', action='store_true', dest='l', help='Love')
parse(
['-i', '-m', 'foo.py'],
(
'Front end-specific options',
'A full description of what these options are for',
callback
),
)
Return a tuple of (config, options, exec_args) wherein "config" is the
config object either parsed from a default/specified config file or default
config options, "options" is the parsed options from
ArgumentParser.parse_args, and "exec_args" are the args (if any) to be parsed
to the executed file (if any).
"""
ifargsisNone:
args=sys.argv[1:]
parser=RaisingArgumentParser(
usage=_(
"Usage: %(prog)s [options] [file [args]]\n"
"NOTE: If bpython sees an argument it does "
"not know, execution falls back to the "
"regular Python interpreter."
)
)
parser.add_argument(
"--config",
default=default_config_path(),
type=Path,
help=_("Use CONFIG instead of default config file."),
)
parser.add_argument(
"--interactive",
"-i",
action="store_true",
help=_("Drop to bpython shell after running file instead of exiting."),
)
parser.add_argument(
"--quiet",
"-q",
action="store_true",
help=_("Don't flush the output to stdout."),
)
parser.add_argument(
"--version",
"-V",
action="store_true",
help=_("Print version and exit."),
)
parser.add_argument(
"--log-level",
"-l",
choices=("debug","info","warning","error","critical"),
default="error",
help=_("Set log level for logging"),
)
parser.add_argument(
"--log-output",
"-L",
help=_("Log output file"),
)
ifextrasisnotNone:
extras_group=parser.add_argument_group(extras[0],extras[1])
extras[2](extras_group)
# collect all the remaining arguments into a list
parser.add_argument(
"args",
nargs=argparse.REMAINDER,
help=_(
"File to execute and additional arguments passed on to the executed script."
),
)
try:
options=parser.parse_args(args)
exceptArgumentParserFailed:
# Just let Python handle this
os.execv(sys.executable, [sys.executable]+args)
ifoptions.version:
print(version_banner())
print(copyright_banner())
raiseSystemExit
ifnotignore_stdinandnot (sys.stdin.isatty()andsys.stdout.isatty()):
# Just let Python handle this
os.execv(sys.executable, [sys.executable]+args)
# Configure logging handler
bpython_logger=logging.getLogger("bpython")
curtsies_logger=logging.getLogger("curtsies")
bpython_logger.setLevel(options.log_level.upper())
curtsies_logger.setLevel(options.log_level.upper())
ifoptions.log_output:
handler=logging.FileHandler(filename=options.log_output)
handler.setFormatter(
logging.Formatter(
"%(asctime)s: %(name)s: %(levelname)s: %(message)s"
)
)
bpython_logger.addHandler(handler)
curtsies_logger.addHandler(handler)
bpython_logger.propagate=curtsies_logger.propagate=False
else:
bpython_logger.addHandler(logging.NullHandler())
curtsies_logger.addHandler(logging.NullHandler())
logger.info(f"Starting bpython{__version__}")
logger.info(f"Python{sys.executable}:{sys.version_info}")
logger.info(f"curtsies:{curtsies.__version__}")
logger.info(f"cwcwidth:{cwcwidth.__version__}")
logger.info(f"greenlet:{greenlet.__version__}")
logger.info(f"pygments:{pygments.__version__}")
logger.info(f"requests:{requests.__version__}")
logger.info(
"environment:\n{}".format(
"\n".join(
f"{key}:{value}"
forkey,valueinsorted(os.environ.items())
ifkey.startswith("LC")
orkey.startswith("LANG")
orkey=="TERM"
)
)
)
returnConfig(options.config),options,options.args
defexec_code(interpreter,args):
"""
Helper to execute code in a given interpreter, e.g. to implement the behavior of python3 [-i] file.py
args should be a [faked] sys.argv.
"""
try:
withopen(args[0])assourcefile:
source=sourcefile.read()
exceptOSErrorase:
# print an error and exit (if -i is specified the calling code will continue)
print(f"bpython: can't open file '{args[0]}:{e}",file=sys.stderr)
raiseSystemExit(e.errno)
old_argv,sys.argv=sys.argv,args
sys.path.insert(0,os.path.abspath(os.path.dirname(args[0])))
spec=importlib.util.spec_from_loader("__console__",loader=None)
mod=importlib.util.module_from_spec(spec)
sys.modules["__console__"]=mod
interpreter.locals.update(mod.__dict__)
interpreter.locals["__file__"]=args[0]
interpreter.runsource(source,args[0],"exec")
sys.argv=old_argv