original_docstring: Handle command-line arguments and run the specified main program.
docstring: Handle command-line arguments and run the specified main program.
docstring_tokens: Handle command - line arguments and run the specified main program .
code: def main():
      """Handle command-line arguments and run the specified main program."""
      parser = argparse.ArgumentParser(description="""Run a Python program or an interactive interpreter with mcpyrate enabled.""",
                                       formatter_class=argparse.RawDescriptionHelpFormatter)
  
      parser.add_argument('-v', '--version', action='version', version=('%(prog)s (mcpyrate ' + __version__ + ')'))
      parser.add_argument(dest='filename', nargs='?', default=None, type=str, metavar='file',
                          help='script to run')
      parser.add_argument('-m', '--module', dest='module', default=None, type=str, metavar='mod',
                          help='run library module as a script (like python -m mod)')
      parser.add_argument('-i', '--interactive', dest='interactive', action="store_true", default=False,
                          help='interactive mode (macro-enabled Python interpreter). '
                               'If -i is given, <filename> and -m <mod> are ignored.')
      parser.add_argument('-p', '--pylab', dest='pylab', action="store_true", default=False,
                          help='For use together with "-i". Automatically "import numpy as np", '
                               '"import matplotlib.pyplot as plt", and enable mpl\'s interactive '
                               'mode (somewhat like IPython\'s pylab mode).')
      opts = parser.parse_args()
  
      if opts.interactive:
          from .console import MacroConsole
          import readline  # noqa: F401, side effect: enable GNU readline in input()
          import rlcompleter  # noqa: F401, side effects: readline tab completion
          repl_locals = {}
          if opts.pylab:  # like IPython's pylab mode, but we keep things in separate namespaces.
              import numpy
              import matplotlib.pyplot
              repl_locals["np"] = numpy
              repl_locals["plt"] = matplotlib.pyplot
              matplotlib.pyplot.ion()
          readline.set_completer(rlcompleter.Completer(namespace=repl_locals).complete)
          readline.parse_and_bind("tab: complete")  # PyPy ignores this, but not needed there.
  
          config_dir = pathlib.Path(_config_dir).expanduser().resolve()
          try:
              readline.read_history_file(config_dir / "macropython_history")
          except FileNotFoundError:
              pass
  
          def save_history():
              config_dir.mkdir(parents=True, exist_ok=True)
              readline.set_history_length(1000)
              readline.write_history_file(config_dir / "macropython_history")
          atexit.register(save_history)
  
          # Add CWD to import path like the builtin interactive console does.
          if sys.path[0] != "":
              sys.path.insert(0, "")
          m = MacroConsole(locals=repl_locals)
          return m.interact()
  
      if not opts.filename and not opts.module:
          parser.print_help()
          sys.exit(0)
      if opts.filename and opts.module:
          raise ValueError("Please specify just one main program to run (either filename.py or -m module, not both).")
  
      # Import the module, pretending its __name__ is "__main__".
      #
      # We must import so that macros get expanded, so we can't use
      # runpy.run_module here (which just execs without importing).
      #
      # As for sys.path, we're not interested in the directory the `macropython`
      # script itself lives in. To imitate how Python itself behaves:
      #
      #   - If run as `macropython -m something`, then `sys.path[0]`
      #     should be set to the cwd.
      #   - If run as `macropython some/path/to/script.py`, then `sys.path[0]`
      #     should be set to the directory containing `script.py`.
      #
      if opts.module:
          # Python 3.7 and later resolve the cwd at interpreter startup time, and use that.
          # Python 3.6 and earlier use the empty string, which dynamically resolves to
          # whatever is the current cwd whenever a module is imported.
          #     https://bugs.python.org/issue33053
          if sys.version_info >= (3, 7, 0):
              cwd = str(pathlib.Path.cwd().expanduser().resolve())
              if sys.path[0] != cwd:
                  sys.path.insert(0, cwd)
          else:
              if sys.path[0] != "":
                  sys.path.insert(0, "")
  
          import_module_as_main(opts.module, script_mode=False)
  
      else:  # no module, so use opts.filename
          fullpath = pathlib.Path(opts.filename).expanduser().resolve()
          if not fullpath.is_file():
              raise FileNotFoundError(f"Can't open file '{opts.filename}'")
  
          containing_directory = str(fullpath.parent)
          if sys.path[0] != containing_directory:
              sys.path.insert(0, containing_directory)
  
          # This approach finds the standard loader even for macro-enabled scripts.
          # TODO: For mcpyrate, that could be ok, since we monkey-patch just that.
          # TODO: But maybe better to leave the option to replace the whole loader later.
          # spec = spec_from_file_location("__main__", str(fullpath))
          # if not spec:
          #     raise ImportError(f"Not a Python module: '{opts.filename}'"
          # module = module_from_spec(spec)
          # TODO: if we use this approach, we should first initialize parent packages.
          # sys.modules[module.__name__] = module
          # spec.loader.exec_module(module)
  
          root_path, relative_path = relativize(opts.filename)
          module_name = relative_path.replace(os.path.sep, '.')
          if module_name.endswith(".__init__.py"):
              module_name = module_name[:-12]
          elif module_name.endswith(".py"):
              module_name = module_name[:-3]
  
          import_module_as_main(module_name, script_mode=True)
code_tokens: def main ( ) : parser = argparse . ArgumentParser ( description = """Run a Python program or an interactive interpreter with mcpyrate enabled.""" , formatter_class = argparse . RawDescriptionHelpFormatter ) parser . add_argument ( '-v' , '--version' , action = 'version' , version = ( '%(prog)s (mcpyrate ' + __version__ + ')' ) ) parser . add_argument ( dest = 'filename' , nargs = '?' , default = None , type = str , metavar = 'file' , help = 'script to run' ) parser . add_argument ( '-m' , '--module' , dest = 'module' , default = None , type = str , metavar = 'mod' , help = 'run library module as a script (like python -m mod)' ) parser . add_argument ( '-i' , '--interactive' , dest = 'interactive' , action = "store_true" , default = False , help = 'interactive mode (macro-enabled Python interpreter). ' 'If -i is given, <filename> and -m <mod> are ignored.' ) parser . add_argument ( '-p' , '--pylab' , dest = 'pylab' , action = "store_true" , default = False , help = 'For use together with "-i". Automatically "import numpy as np", ' '"import matplotlib.pyplot as plt", and enable mpl\'s interactive ' 'mode (somewhat like IPython\'s pylab mode).' ) opts = parser . parse_args ( ) if opts . interactive : from . console import MacroConsole import readline import rlcompleter repl_locals = { } if opts . pylab : import numpy import matplotlib . pyplot repl_locals [ "np" ] = numpy repl_locals [ "plt" ] = matplotlib . pyplot matplotlib . pyplot . ion ( ) readline . set_completer ( rlcompleter . Completer ( namespace = repl_locals ) . complete ) readline . parse_and_bind ( "tab: complete" ) config_dir = pathlib . Path ( _config_dir ) . expanduser ( ) . resolve ( ) try : readline . read_history_file ( config_dir / "macropython_history" ) except FileNotFoundError : pass def save_history ( ) : config_dir . mkdir ( parents = True , exist_ok = True ) readline . set_history_length ( 1000 ) readline . write_history_file ( config_dir / "macropython_history" ) atexit . register ( save_history ) if sys . path [ 0 ] != "" : sys . path . insert ( 0 , "" ) m = MacroConsole ( locals = repl_locals ) return m . interact ( ) if not opts . filename and not opts . module : parser . print_help ( ) sys . exit ( 0 ) if opts . filename and opts . module : raise ValueError ( "Please specify just one main program to run (either filename.py or -m module, not both)." ) if opts . module : if sys . version_info >= ( 3 , 7 , 0 ) : cwd = str ( pathlib . Path . cwd ( ) . expanduser ( ) . resolve ( ) ) if sys . path [ 0 ] != cwd : sys . path . insert ( 0 , cwd ) else : if sys . path [ 0 ] != "" : sys . path . insert ( 0 , "" ) import_module_as_main ( opts . module , script_mode = False ) else : fullpath = pathlib . Path ( opts . filename ) . expanduser ( ) . resolve ( ) if not fullpath . is_file ( ) : raise FileNotFoundError ( f"Can't open file '{opts.filename}'" ) containing_directory = str ( fullpath . parent ) if sys . path [ 0 ] != containing_directory : sys . path . insert ( 0 , containing_directory ) root_path , relative_path = relativize ( opts . filename ) module_name = relative_path . replace ( os . path . sep , '.' ) if module_name . endswith ( ".__init__.py" ) : module_name = module_name [ : - 12 ] elif module_name . endswith ( ".py" ) : module_name = module_name [ : - 3 ] import_module_as_main ( module_name , script_mode = True )
short_docstring: Handle command-line arguments and run the specified main program.
short_docstring_tokens: Handle command - line arguments and run the specified main program .
comment: """Handle command-line arguments and run the specified main program."""$SEP$# noqa: F401, side effect: enable GNU readline in input()$SEP$# noqa: F401, side effects: readline tab completion$SEP$# like IPython's pylab mode, but we keep things in separate namespaces.$SEP$# PyPy ignores this, but not needed there.$SEP$# Add CWD to import path like the builtin interactive console does.$SEP$# Import the module, pretending its __name__ is "__main__".$SEP$#$SEP$# We must import so that macros get expanded, so we can't use$SEP$# runpy.run_module here (which just execs without importing).$SEP$#$SEP$# As for sys.path, we're not interested in the directory the `macropython`$SEP$# script itself lives in. To imitate how Python itself behaves:$SEP$#$SEP$#   - If run as `macropython -m something`, then `sys.path[0]`$SEP$#     should be set to the cwd.$SEP$#   - If run as `macropython some/path/to/script.py`, then `sys.path[0]`$SEP$#     should be set to the directory containing `script.py`.$SEP$#$SEP$# Python 3.7 and later resolve the cwd at interpreter startup time, and use that.$SEP$# Python 3.6 and earlier use the empty string, which dynamically resolves to$SEP$# whatever is the current cwd whenever a module is imported.$SEP$#     https://bugs.python.org/issue33053$SEP$# no module, so use opts.filename$SEP$# This approach finds the standard loader even for macro-enabled scripts.$SEP$# TODO: For mcpyrate, that could be ok, since we monkey-patch just that.$SEP$# TODO: But maybe better to leave the option to replace the whole loader later.$SEP$# spec = spec_from_file_location("__main__", str(fullpath))$SEP$# if not spec:$SEP$#     raise ImportError(f"Not a Python module: '{opts.filename}'"$SEP$# module = module_from_spec(spec)$SEP$# TODO: if we use this approach, we should first initialize parent packages.$SEP$# sys.modules[module.__name__] = module$SEP$# spec.loader.exec_module(module)