Example #1
0
def hy2py_main():
    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:])

    if options.FILE is None or options.FILE == '-':
        sys.path.insert(0, "")
        filename = '<stdin>'
        source = sys.stdin.read()
    else:
        filename = options.FILE
        set_path(filename)
        with io.open(options.FILE, 'r', encoding='utf-8') as source_file:
            source = source_file.read()

    with filtered_hy_exceptions():
        hst = hy_parse(source, filename=filename)

    if options.with_source:
        _print_for_windows(hst)
        print()
        print()

    with filtered_hy_exceptions():
        _ast = hy_compile(hst, '__main__', filename=filename, source=source)

    if options.with_ast:
        _print_for_windows(ast.dump(_ast))
        print()
        print()

    if not options.without_python:
        _print_for_windows(ast.unparse(_ast))

    parser.exit(0)
Example #2
0
File: cmdline.py Project: jams2/hy
def run_icommand(source, **kwargs):
    if os.path.exists(source):
        # Emulate Python cmdline behavior by setting `sys.path` relative
        # to the executed file's location.
        if sys.path[0] == '':
            sys.path[0] = os.path.realpath(os.path.split(source)[0])
        else:
            sys.path.insert(0, os.path.split(source)[0])

        with io.open(source, "r", encoding='utf-8') as f:
            source = f.read()
        filename = source
    else:
        filename = '<string>'

    hr = HyREPL(**kwargs)
    with filtered_hy_exceptions():
        res = hr.runsource(source, filename=filename)

    # If the command was prematurely ended, show an error (just like Python
    # does).
    if res:
        hy_exc_handler(sys.last_type, sys.last_value, sys.last_traceback)

    return run_repl(hr)
Example #3
0
File: cmdline.py Project: hylang/hy
def run_icommand(source, **kwargs):
    if os.path.exists(source):
        # Emulate Python cmdline behavior by setting `sys.path` relative
        # to the executed file's location.
        if sys.path[0] == '':
            sys.path[0] = os.path.realpath(os.path.split(source)[0])
        else:
            sys.path.insert(0, os.path.split(source)[0])

        with io.open(source, "r", encoding='utf-8') as f:
            source = f.read()
        filename = source
    else:
        filename = '<string>'

    hr = HyREPL(**kwargs)
    with filtered_hy_exceptions():
        res = hr.runsource(source, filename=filename)

    # If the command was prematurely ended, show an error (just like Python
    # does).
    if res:
        hy_exc_handler(sys.last_type, sys.last_value, sys.last_traceback)

    return run_repl(hr)
Example #4
0
def run_command(source, filename=None):
    __main__ = importlib.import_module('__main__')
    require("hy.cmdline", __main__, assignments="ALL")
    try:
        tree = hy_parse(source, filename=filename)
    except HyLanguageError:
        hy_exc_handler(*sys.exc_info())
        return 1

    with filtered_hy_exceptions():
        hy_eval(tree, None, __main__, filename=filename, source=source)
    return 0
Example #5
0
File: cmdline.py Project: hylang/hy
def run_command(source, filename=None):
    __main__ = importlib.import_module('__main__')
    require("hy.cmdline", __main__, assignments="ALL")
    try:
        tree = hy_parse(source, filename=filename)
    except HyLanguageError:
        hy_exc_handler(*sys.exc_info())
        return 1

    with filtered_hy_exceptions():
        hy_eval(tree, None, __main__, filename=filename, source=source)
    return 0
Example #6
0
def run_icommand(source, **kwargs):
    if os.path.exists(source):
        set_path(source)
        with io.open(source, "r", encoding='utf-8') as f:
            source = f.read()
        filename = source
    else:
        filename = '<string>'

    hr = HyREPL(**kwargs)
    with filtered_hy_exceptions():
        res = hr.runsource(source, filename=filename)

    # If the command was prematurely ended, show an error (just like Python
    # does).
    if res:
        hy_exc_handler(sys.last_type, sys.last_value, sys.last_traceback)

    return run_repl(hr)
Example #7
0
File: cmdline.py Project: jams2/hy
def run_repl(hr=None, **kwargs):
    import platform
    sys.ps1 = "=> "
    sys.ps2 = "... "

    if not hr:
        hr = HyREPL(**kwargs)

    namespace = hr.locals
    with filtered_hy_exceptions(), \
         extend_linecache(hr.cmdline_cache), \
         completion(Completer(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
Example #8
0
File: cmdline.py Project: hylang/hy
def run_repl(hr=None, **kwargs):
    import platform
    sys.ps1 = "=> "
    sys.ps2 = "... "

    if not hr:
        hr = HyREPL(**kwargs)

    namespace = hr.locals
    with filtered_hy_exceptions(), \
         extend_linecache(hr.cmdline_cache), \
         completion(Completer(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
Example #9
0
File: cmdline.py Project: jams2/hy
def hy2py_main():
    import platform

    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:])

    if options.FILE is None or options.FILE == '-':
        filename = '<stdin>'
        source = sys.stdin.read()
    else:
        filename = options.FILE
        with io.open(options.FILE, 'r', encoding='utf-8') as source_file:
            source = source_file.read()

    with filtered_hy_exceptions():
        hst = hy_parse(source, filename=filename)

    if options.with_source:
        # need special printing on Windows in case the
        # codepage doesn't support utf-8 characters
        if platform.system() == "Windows":
            for h in hst:
                try:
                    print(h)
                except:
                    print(str(h).encode('utf-8'))
        else:
            print(hst)
        print()
        print()

    with filtered_hy_exceptions():
        _ast = hy_compile(hst, '__main__', filename=filename, source=source)

    if options.with_ast:
        if platform.system() == "Windows":
            _print_for_windows(astor.dump_tree(_ast))
        else:
            print(astor.dump_tree(_ast))
        print()
        print()

    if not options.without_python:
        if platform.system() == "Windows":
            _print_for_windows(astor.code_gen.to_source(_ast))
        else:
            print(astor.code_gen.to_source(_ast))

    parser.exit(0)
Example #10
0
File: cmdline.py Project: jams2/hy
def cmdline_handler(scriptname, argv):
    # We need to terminate interpretation of options after certain
    # options, such as `-c`. So, we can't use `argparse`.

    defs = [
        dict(name=["-h", "--help"],
             action="help",
             help="show this help message and exit"),
        dict(name=["-c"],
             dest="command",
             terminate=True,
             help="program passed in as a string"),
        dict(name=["-m"],
             dest="mod",
             terminate=True,
             help="module to run, passed in as a string"),
        dict(name=["-E"],
             action='store_true',
             help="ignore PYTHON* environment variables"),
        dict(
            name=["-B"],
            action='store_true',
            help=
            "don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x"
        ),
        dict(name=["-i"],
             dest="icommand",
             terminate=True,
             help="program passed in as a string, then stay in REPL"),
        dict(name=["--spy"],
             action="store_true",
             help="print equivalent Python code before executing"),
        dict(name=["--repl-output-fn"],
             dest="repl_output_fn",
             help="function for printing REPL output "
             "(e.g., hy.contrib.hy-repr.hy-repr)"),
        dict(name=["-v", "--version"],
             action="version",
             help="show program's version number and exit")
    ]

    # Get the path of the Hy cmdline executable and swap it with
    # `sys.executable` (saving the original, just in case).
    # XXX: The `__main__` module will also have `__file__` set to the
    # entry-point script.  Currently, I don't see an immediate problem, but
    # that's not how the Python cmdline works.
    hy.executable = argv[0]
    hy.sys_executable = sys.executable
    sys.executable = hy.executable

    program = argv[0]
    argv = list(argv[1:])
    options = {}

    def err(fmt, *args):
        raise HyArgError('hy: ' + fmt.format(*args))

    def proc_opt(opt, arg=None, item=None, i=None):
        matches = [o for o in defs if opt in o['name']]
        if not matches:
            err('unrecognized option: {}', opt)
        [match] = matches
        if 'dest' in match:
            if arg:
                pass
            elif i is not None and i + 1 < len(item):
                arg = item[i + 1 + (item[i + 1] == '='):]
            elif argv:
                arg = argv.pop(0)
            else:
                err('option {}: expected one argument', opt)
            options[match['dest']] = arg
        else:
            options[match['name'][-1].lstrip('-')] = True
        if 'terminate' in match:
            return 'terminate'
        return 'dest' in match

    # Collect options.
    while argv:
        item = argv.pop(0)
        if item == '--':
            break
        elif item.startswith('--'):
            # One double-hyphen option.
            opt, _, arg = item.partition('=')
            if proc_opt(opt, arg=arg) == 'terminate':
                break
        elif item.startswith('-') and item != '-':
            # One or more single-hyphen options.
            for i in range(1, len(item)):
                x = proc_opt('-' + item[i], item=item, i=i)
                if x:
                    break
            if x == 'terminate':
                break
        else:
            # We're done with options. Add the item back.
            argv.insert(0, item)
            break

    if 'E' in options:
        _remove_python_envs()

    if 'B' in options:
        sys.dont_write_bytecode = True

    if 'help' in options:
        print('usage:', USAGE)
        print('')
        print('optional arguments:')
        for o in defs:
            print(', '.join(o['name']) +
                  ('=' + o['dest'].upper() if 'dest' in o else ''))
            print('    ' + o['help'] +
                  (' (terminates option list)' if o.get('terminate') else ''))
        print(EPILOG)
        return 0

    if 'version' in options:
        print(VERSION)
        return 0

    if 'command' in options:
        sys.argv = ['-c'] + argv
        return run_command(options['command'], filename='<string>')

    if 'mod' in options:
        sys.argv = [program] + argv
        runpy.run_module(options['mod'], run_name='__main__', alter_sys=True)
        return 0

    if 'icommand' in options:
        return run_icommand(options['icommand'],
                            spy=options.get('spy'),
                            output_fn=options.get('repl_output_fn'))

    if argv:
        if argv[0] == "-":
            # Read the program from stdin
            return run_command(sys.stdin.read(), filename='<stdin>')

        else:
            # User did "hy <filename>"
            filename = argv[0]

            # Emulate Python cmdline behavior by setting `sys.path` relative
            # to the executed file's location.
            if sys.path[0] == '':
                sys.path[0] = os.path.realpath(os.path.split(filename)[0])
            else:
                sys.path.insert(0, os.path.split(filename)[0])

            try:
                sys.argv = argv
                with filtered_hy_exceptions():
                    runhy.run_path(filename, run_name='__main__')
                return 0
            except FileNotFoundError as e:
                print("hy: Can't open file '{0}': [Errno {1}] {2}".format(
                    e.filename, e.errno, e.strerror),
                      file=sys.stderr)
                sys.exit(e.errno)
            except HyLanguageError:
                hy_exc_handler(*sys.exc_info())
                sys.exit(1)

    return run_repl(spy=options.get('spy'),
                    output_fn=options.get('repl_output_fn'))
Example #11
0
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("-E",
                        action='store_true',
                        help="ignore PYTHON* environment variables")
    parser.add_argument(
        "-B",
        action='store_true',
        help=
        "don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x")
    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("--repl-output-fn",
                        help="function for printing REPL output "
                        "(e.g., hy.contrib.hy-repr.hy-repr)")
    parser.add_argument("-v", "--version", action="version", version=VERSION)

    # this will contain the script/program name and any arguments for it.
    parser.add_argument('args',
                        nargs=argparse.REMAINDER,
                        help=argparse.SUPPRESS)

    # Get the path of the Hy cmdline executable and swap it with
    # `sys.executable` (saving the original, just in case).
    # XXX: The `__main__` module will also have `__file__` set to the
    # entry-point script.  Currently, I don't see an immediate problem, but
    # that's not how the Python cmdline works.
    hy.executable = argv[0]
    hy.sys_executable = sys.executable
    sys.executable = hy.executable

    # 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.E:
        # User did "hy -E ..."
        _remove_python_envs()

    if options.B:
        sys.dont_write_bytecode = True

    if options.command:
        # User did "hy -c ..."
        return run_command(options.command, filename='<string>')

    if options.mod:
        # User did "hy -m ..."
        sys.argv = [sys.argv[0]] + options.args + module_args
        runpy.run_module(options.mod, run_name='__main__', alter_sys=True)
        return 0

    if options.icommand:
        # User did "hy -i ..."
        return run_icommand(options.icommand,
                            spy=options.spy,
                            output_fn=options.repl_output_fn)

    if options.args:
        if options.args[0] == "-":
            # Read the program from stdin
            return run_command(sys.stdin.read(), filename='<stdin>')

        else:
            # User did "hy <filename>"
            filename = options.args[0]

            # Emulate Python cmdline behavior by setting `sys.path` relative
            # to the executed file's location.
            if sys.path[0] == '':
                sys.path[0] = os.path.realpath(os.path.split(filename)[0])
            else:
                sys.path.insert(0, os.path.split(filename)[0])

            try:
                sys.argv = options.args
                with filtered_hy_exceptions():
                    runhy.run_path(filename, run_name='__main__')
                return 0
            except FileNotFoundError as e:
                print("hy: Can't open file '{0}': [Errno {1}] {2}".format(
                    e.filename, e.errno, e.strerror),
                      file=sys.stderr)
                sys.exit(e.errno)
            except HyLanguageError:
                hy_exc_handler(*sys.exc_info())
                sys.exit(1)

    # User did NOTHING!
    return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
Example #12
0
File: cmdline.py Project: hylang/hy
def hy2py_main():
    import platform

    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:])

    if options.FILE is None or options.FILE == '-':
        filename = '<stdin>'
        source = sys.stdin.read()
    else:
        filename = options.FILE
        with io.open(options.FILE, 'r', encoding='utf-8') as source_file:
            source = source_file.read()

    with filtered_hy_exceptions():
        hst = hy_parse(source, filename=filename)

    if options.with_source:
        # 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()

    with filtered_hy_exceptions():
        _ast = hy_compile(hst, '__main__', filename=filename, source=source)

    if options.with_ast:
        if PY3 and platform.system() == "Windows":
            _print_for_windows(astor.dump_tree(_ast))
        else:
            print(astor.dump_tree(_ast))
        print()
        print()

    if not options.without_python:
        if PY3 and platform.system() == "Windows":
            _print_for_windows(astor.code_gen.to_source(_ast))
        else:
            print(astor.code_gen.to_source(_ast))

    parser.exit(0)
Example #13
0
File: cmdline.py Project: hylang/hy
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("-E", action='store_true',
                        help="ignore PYTHON* environment variables")
    parser.add_argument("-B", action='store_true',
                        help="don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x")
    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("--repl-output-fn",
                        help="function for printing REPL output "
                             "(e.g., hy.contrib.hy-repr.hy-repr)")
    parser.add_argument("-v", "--version", action="version", version=VERSION)

    # this will contain the script/program name and any arguments for it.
    parser.add_argument('args', nargs=argparse.REMAINDER,
                        help=argparse.SUPPRESS)

    # Get the path of the Hy cmdline executable and swap it with
    # `sys.executable` (saving the original, just in case).
    # XXX: The `__main__` module will also have `__file__` set to the
    # entry-point script.  Currently, I don't see an immediate problem, but
    # that's not how the Python cmdline works.
    hy.executable = argv[0]
    hy.sys_executable = sys.executable
    sys.executable = hy.executable

    # 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.E:
        # User did "hy -E ..."
        _remove_python_envs()

    if options.B:
        sys.dont_write_bytecode = True

    if options.command:
        # User did "hy -c ..."
        return run_command(options.command, filename='<string>')

    if options.mod:
        # User did "hy -m ..."
        sys.argv = [sys.argv[0]] + options.args + module_args
        runpy.run_module(options.mod, run_name='__main__', alter_sys=True)
        return 0

    if options.icommand:
        # User did "hy -i ..."
        return run_icommand(options.icommand, spy=options.spy,
                            output_fn=options.repl_output_fn)

    if options.args:
        if options.args[0] == "-":
            # Read the program from stdin
            return run_command(sys.stdin.read(), filename='<stdin>')

        else:
            # User did "hy <filename>"
            filename = options.args[0]

            # Emulate Python cmdline behavior by setting `sys.path` relative
            # to the executed file's location.
            if sys.path[0] == '':
                sys.path[0] = os.path.realpath(os.path.split(filename)[0])
            else:
                sys.path.insert(0, os.path.split(filename)[0])

            try:
                sys.argv = options.args
                with filtered_hy_exceptions():
                    runhy.run_path(filename, run_name='__main__')
                return 0
            except FileNotFoundError as e:
                print("hy: Can't open file '{0}': [Errno {1}] {2}".format(
                      e.filename, e.errno, e.strerror), file=sys.stderr)
                sys.exit(e.errno)
            except HyLanguageError:
                hy_exc_handler(*sys.exc_info())
                sys.exit(1)

    # User did NOTHING!
    return run_repl(spy=options.spy, output_fn=options.repl_output_fn)