/usr/lib/python2.7/dist-packages/hy/cmdline.py is in python-hy 0.12.1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | # Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Gergely Nagy <algernon@madhouse-project.org>
# Copyright (c) 2013 James King <james@agentultra.com>
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Konrad Hinsen <konrad.hinsen@fastmail.net>
# Copyright (c) 2013 Thom Neale <twneale@gmail.com>
# Copyright (c) 2013 Will Kahn-Greene <willg@bluesock.org>
# Copyright (c) 2013 Bob Tolbert <bob@tolbert.org>
#
# 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.
from __future__ import print_function
import argparse
import code
import ast
import sys
import os
import astor.codegen
import hy
from hy.lex import LexException, PrematureEndOfInput, tokenize
from hy.compiler import hy_compile, HyTypeError
from hy.importer import (ast_compile, import_buffer_to_module,
import_file_to_ast, import_file_to_hst,
import_buffer_to_ast, import_buffer_to_hst)
from hy.completer import completion
from hy.completer import Completer
from hy.errors import HyIOError
from hy.macros import macro, require
from hy.models.expression import HyExpression
from hy.models.string import HyString
from hy.models.symbol import HySymbol
from hy._compat import builtins, PY3
class HyQuitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "Use (%s) or Ctrl-D (i.e. EOF) to exit" % (self.name)
__str__ = __repr__
def __call__(self, code=None):
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
builtins.quit = HyQuitter('quit')
builtins.exit = HyQuitter('exit')
def print_python_code(_ast):
# astor cannot handle ast.Interactive, so disguise it as a module
_ast_for_print = ast.Module()
_ast_for_print.body = _ast.body
print(astor.codegen.to_source(_ast_for_print))
class HyREPL(code.InteractiveConsole):
def __init__(self, spy=False, locals=None, filename="<input>"):
self.spy = spy
code.InteractiveConsole.__init__(self, locals=locals,
filename=filename)
def runsource(self, source, filename='<input>', symbol='single'):
global SIMPLE_TRACEBACKS
try:
tokens = tokenize(source)
except PrematureEndOfInput:
return True
except LexException as e:
if e.source is None:
e.source = source
e.filename = filename
print(e, file=sys.stderr)
return False
try:
_ast = hy_compile(tokens, "__console__", root=ast.Interactive)
if self.spy:
print_python_code(_ast)
code = ast_compile(_ast, filename, symbol)
except HyTypeError as e:
if e.source is None:
e.source = source
e.filename = filename
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
else:
self.showtraceback()
return False
except Exception:
self.showtraceback()
return False
self.runcode(code)
return False
@macro("koan")
def koan_macro():
return HyExpression([HySymbol('print'),
HyString("""
Ummon asked the head monk, "What sutra are you lecturing on?"
"The Nirvana Sutra."
"The Nirvana Sutra has the Four Virtues, hasn't it?"
"It has."
Ummon asked, picking up a cup, "How many virtues has this?"
"None at all," said the monk.
"But ancient people said it had, didn't they?" said Ummon.
"What do you think of what they said?"
Ummon struck the cup and asked, "You understand?"
"No," said the monk.
"Then," said Ummon, "You'd better go on with your lectures on the sutra."
""")])
@macro("ideas")
def ideas_macro():
return HyExpression([HySymbol('print'),
HyString(r"""
=> (import [sh [figlet]])
=> (figlet "Hi, Hy!")
_ _ _ _ _ _
| | | (_) | | | |_ _| |
| |_| | | | |_| | | | | |
| _ | |_ | _ | |_| |_|
|_| |_|_( ) |_| |_|\__, (_)
|/ |___/
;;; string things
(.join ", " ["what" "the" "heck"])
;;; this one plays with command line bits
(import [sh [cat grep]])
(-> (cat "/usr/share/dict/words") (grep "-E" "bro$"))
;;; filtering a list w/ a lambda
(filter (lambda [x] (= (% x 2) 0)) (range 0 10))
;;; swaggin' functional bits (Python rulez)
(max (map (lambda [x] (len x)) ["hi" "my" "name" "is" "paul"]))
""")])
require("hy.cmdline", "__console__", all_macros=True)
require("hy.cmdline", "__main__", all_macros=True)
SIMPLE_TRACEBACKS = True
def pretty_error(func, *args, **kw):
try:
return func(*args, **kw)
except (HyTypeError, LexException) as e:
if SIMPLE_TRACEBACKS:
print(e, file=sys.stderr)
sys.exit(1)
raise
def run_command(source):
pretty_error(import_buffer_to_module, "__main__", source)
return 0
def run_module(mod_name):
from hy.importer import MetaImporter
pth = MetaImporter().find_on_path(mod_name)
if pth is not None:
sys.argv = [pth] + sys.argv
return run_file(pth)
print("{0}: module '{1}' not found.\n".format(hy.__appname__, mod_name),
file=sys.stderr)
return 1
def run_file(filename):
from hy.importer import import_file_to_module
pretty_error(import_file_to_module, "__main__", filename)
return 0
def run_repl(hr=None, spy=False):
import platform
sys.ps1 = "=> "
sys.ps2 = "... "
namespace = {'__name__': '__console__', '__doc__': ''}
with completion(Completer(namespace)):
if not hr:
hr = HyREPL(spy, namespace)
hr.interact("{appname} {version} using "
"{py}({build}) {pyversion} on {os}".format(
appname=hy.__appname__,
version=hy.__version__,
py=platform.python_implementation(),
build=platform.python_build()[0],
pyversion=platform.python_version(),
os=platform.system()
))
return 0
def run_icommand(source, spy=False):
hr = HyREPL(spy)
if os.path.exists(source):
with open(source, "r") as f:
source = f.read()
filename = source
else:
filename = '<input>'
hr.runsource(source, filename=filename, symbol='single')
return run_repl(hr)
USAGE = "%(prog)s [-h | -i cmd | -c cmd | -m module | file | -] [arg] ..."
VERSION = "%(prog)s " + hy.__version__
EPILOG = """ file program read from script
module module to execute as main
- program read from stdin
[arg] ... arguments passed to program in sys.argv[1:]
"""
def cmdline_handler(scriptname, argv):
parser = argparse.ArgumentParser(
prog="hy",
usage=USAGE,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=EPILOG)
parser.add_argument("-c", dest="command",
help="program passed in as a string")
parser.add_argument("-m", dest="mod",
help="module to run, passed in as a string")
parser.add_argument(
"-i", dest="icommand",
help="program passed in as a string, then stay in REPL")
parser.add_argument("--spy", action="store_true",
help="print equivalent Python code before executing")
parser.add_argument("-v", "--version", action="version", version=VERSION)
parser.add_argument("--show-tracebacks", action="store_true",
help="show complete tracebacks for Hy exceptions")
# this will contain the script/program name and any arguments for it.
parser.add_argument('args', nargs=argparse.REMAINDER,
help=argparse.SUPPRESS)
# stash the hy executable in case we need it later
# mimics Python sys.executable
hy.executable = argv[0]
# need to split the args if using "-m"
# all args after the MOD are sent to the module
# in sys.argv
module_args = []
if "-m" in argv:
mloc = argv.index("-m")
if len(argv) > mloc+2:
module_args = argv[mloc+2:]
argv = argv[:mloc+2]
options = parser.parse_args(argv[1:])
if options.show_tracebacks:
global SIMPLE_TRACEBACKS
SIMPLE_TRACEBACKS = False
# reset sys.argv like Python
sys.argv = options.args + module_args or [""]
if options.command:
# User did "hy -c ..."
return run_command(options.command)
if options.mod:
# User did "hy -m ..."
return run_module(options.mod)
if options.icommand:
# User did "hy -i ..."
return run_icommand(options.icommand, spy=options.spy)
if options.args:
if options.args[0] == "-":
# Read the program from stdin
return run_command(sys.stdin.read())
else:
# User did "hy <filename>"
try:
return run_file(options.args[0])
except HyIOError as e:
print("hy: Can't open file '{0}': [Errno {1}] {2}\n".format(
e.filename, e.errno, e.strerror), file=sys.stderr)
sys.exit(e.errno)
# User did NOTHING!
return run_repl(spy=options.spy)
# entry point for cmd line script "hy"
def hy_main():
sys.exit(cmdline_handler("hy", sys.argv))
# entry point for cmd line script "hyc"
def hyc_main():
from hy.importer import write_hy_as_pyc
parser = argparse.ArgumentParser(prog="hyc")
parser.add_argument("files", metavar="FILE", nargs='+',
help="file to compile")
parser.add_argument("-v", action="version", version=VERSION)
options = parser.parse_args(sys.argv[1:])
for file in options.files:
try:
print("Compiling %s" % file)
pretty_error(write_hy_as_pyc, file)
except IOError as x:
print("hyc: Can't open file '{0}': [Errno {1}] {2}\n".format(
x.filename, x.errno, x.strerror), file=sys.stderr)
sys.exit(x.errno)
# entry point for cmd line script "hy2py"
def hy2py_main():
import platform
module_name = "<STDIN>"
options = dict(prog="hy2py", usage="%(prog)s [options] [FILE]",
formatter_class=argparse.RawDescriptionHelpFormatter)
parser = argparse.ArgumentParser(**options)
parser.add_argument("FILE", type=str, nargs='?',
help="Input Hy code (use STDIN if \"-\" or "
"not provided)")
parser.add_argument("--with-source", "-s", action="store_true",
help="Show the parsed source structure")
parser.add_argument("--with-ast", "-a", action="store_true",
help="Show the generated AST")
parser.add_argument("--without-python", "-np", action="store_true",
help=("Do not show the Python code generated "
"from the AST"))
options = parser.parse_args(sys.argv[1:])
stdin_text = None
if options.FILE is None or options.FILE == '-':
stdin_text = sys.stdin.read()
if options.with_source:
hst = (pretty_error(import_file_to_hst, options.FILE)
if stdin_text is None
else pretty_error(import_buffer_to_hst, stdin_text))
# need special printing on Windows in case the
# codepage doesn't support utf-8 characters
if PY3 and platform.system() == "Windows":
for h in hst:
try:
print(h)
except:
print(str(h).encode('utf-8'))
else:
print(hst)
print()
print()
_ast = (pretty_error(import_file_to_ast, options.FILE, module_name)
if stdin_text is None
else pretty_error(import_buffer_to_ast, stdin_text, module_name))
if options.with_ast:
if PY3 and platform.system() == "Windows":
_print_for_windows(astor.dump(_ast))
else:
print(astor.dump(_ast))
print()
print()
if not options.without_python:
if PY3 and platform.system() == "Windows":
_print_for_windows(astor.codegen.to_source(_ast))
else:
print(astor.codegen.to_source(_ast))
parser.exit(0)
# need special printing on Windows in case the
# codepage doesn't support utf-8 characters
def _print_for_windows(src):
for line in src.split("\n"):
try:
print(line)
except:
print(line.encode('utf-8'))
|