示例#1
0
 def _cmd_Run(self, cmd):
     report_time("Before Run")
     self.switch_env_to_script_mode(cmd)
     try:
         return self._execute_file(cmd, SimpleRunner)
     finally:
         report_time("After Run")
示例#2
0
 def _cmd_execute_source(self, cmd):
     # TODO: clear last object inspector requests dictionary
     if cmd.source:
         source = self._add_expression_statement_handlers(cmd.source)
         report_time("befexeccc")
         self._execute(source, capture_output=False)
         self._check_prepare()
         report_time("affexeccc")
     # TODO: assign last value to _
     return {}
示例#3
0
    def _handle_normal_command(self, cmd: CommandToBackend) -> None:
        logger.debug("Handling normal command '%s' in micropython backend ",
                     cmd.name)
        report_time("before " + cmd.name)

        if "local_cwd" in cmd:
            self._local_cwd = cmd["local_cwd"]

        super()._handle_normal_command(cmd)

        self._check_perform_just_in_case_gc()
        report_time("after " + cmd.name)
示例#4
0
    def _process_until_initial_prompt(self, interrupt, clean):
        # This will be called only when the interpreter gets run without script.
        # (%Run script.py does not create a new instance of this class)
        output = []

        def collect_output(data, stream_name):
            output.append(data)

        report_time("befini")
        self._forward_output_until_active_prompt(collect_output, "stdout")
        self._original_welcome_text = "".join(output).replace("\r\n", "\n")
        self._welcome_text = self._tweak_welcome_text(
            self._original_welcome_text)
        report_time("afini")
示例#5
0
    def _prepare_after_soft_reboot(self, clean=False):
        report_time("bef preparing helpers")
        logger.info("Preparing helpers")
        script = self._get_helper_code()
        logger.debug("Helper code:\n%s", script)
        self._check_perform_just_in_case_gc()
        self._execute_without_output(script)
        # self._execute_without_output(
        #     dedent(
        #         """
        #     for key in __thonny_helper.builtins.dir(__thonny_helper.builtins):
        #         if not key.startswith("__"):
        #             __thonny_helper.builtins.globals()[key] = None
        #     """
        #     ).strip()
        # )
        report_time("prepared helpers")

        self._update_cwd()
        report_time("got cwd")
        self._sys_path = self._fetch_sys_path()

        report_time("prepared")
        self._check_perform_just_in_case_gc()
        logger.info("Prepared")
示例#6
0
    def __init__(self, target_cwd):
        report_time("Before MainBackend")
        MainBackend.__init__(self)
        report_time("After MainBackend")

        global _backend
        _backend = self

        self._ini = None
        self._object_info_tweakers = []
        self._import_handlers = {}
        self._input_queue = queue.Queue()
        self._source_preprocessors = []
        self._ast_postprocessors = []
        self._main_dir = os.path.dirname(sys.modules["thonny"].__file__)
        self._heap = {
        }  # WeakValueDictionary would be better, but can't store reference to None
        self._source_info_by_frame = {}
        site.sethelper()  # otherwise help function is not available
        self._install_fake_streams()
        self._install_repl_helper()
        self._current_executor = None
        self._io_level = 0
        self._tty_mode = True
        self._tcl = None

        update_system_path(os.environ,
                           get_augmented_system_path(get_exe_dirs()))

        # clean __main__ global scope
        for key in list(__main__.__dict__.keys()):
            if not key.startswith("__") or key in {"__file__", "__cached__"}:
                del __main__.__dict__[key]

        # unset __doc__, then exec dares to write doc of the script there
        __main__.__doc__ = None

        logger.info("Loading plugins")
        report_time("Before loading plugins")
        execute_with_frontend_sys_path(self._load_plugins)
        report_time("After loading plugins")

        # preceding code was run in the directory containing thonny module, now switch to provided
        try:
            os.chdir(os.path.expanduser(target_cwd))
        except OSError:
            try:
                os.chdir(os.path.expanduser("~"))
            except OSError:
                os.chdir("/")  # yes, this works also in Windows

        # ... and replace current-dir path item
        # start in shell mode (may be later switched to script mode)
        # required in shell mode and also required to overwrite thonny location dir
        sys.path[0] = ""
        sys.argv[:] = [""]  # empty "script name"

        if os.name == "nt":
            self._install_signal_handler()
示例#7
0
    def _cmd_Run(self, cmd):
        self._connection.close()
        report_time("befconn")
        args = cmd.args
        if cmd.source and args[0] == "-c":
            if len(args) > 1:
                self._send_error_message(
                    "Warning: MicroPython doesn't allow program arguments (%s) together with '-c'"
                    % " ".join(map(shlex.quote, args[1:])))
            args = ["-c", cmd.source]

        self._connection = self._create_connection(args)
        report_time("afconn")
        self._forward_output_until_active_prompt(self._send_output, "stdout")
        report_time("afforv")
        self.send_message(
            BackendEvent(event_type="HideTrailingOutput",
                         text=self._original_welcome_text))
        report_time("beffhelp")
        self._prepare_after_soft_reboot()
        report_time("affhelp")
示例#8
0
    def __init__(self, clean, args):
        logger.info("Initializing MicroPythonBackend of type %s",
                    type(self).__name__)
        self._connection: MicroPythonConnection
        self._args = args
        self._last_interrupt_time = None
        self._local_cwd = None
        self._cwd = args.get("cwd")
        self._progress_times = {}
        self._welcome_text = None
        self._sys_path = None
        self._epoch_year = None
        self._builtin_modules = []
        self._number_of_interrupts_sent = 0

        self._builtins_info = self._fetch_builtins_info()

        MainBackend.__init__(self)
        try:
            report_time("before prepare")
            self._process_until_initial_prompt(
                interrupt=args["interrupt_on_connect"] or clean, clean=clean)
            if self._welcome_text is None:
                self._welcome_text = self._fetch_welcome_text()
                report_time("got welcome")

            # Get rid of the welcome text which was printed while searching for prompt
            self.send_message(
                BackendEvent(event_type="HideTrailingOutput",
                             text=self._welcome_text))

            self._prepare_after_soft_reboot(clean)

            if not self._builtin_modules:
                self._builtin_modules = self._fetch_builtin_modules()
                logger.debug("Built-in modules: %s", self._builtin_modules)

            self._prepare_rtc()
            self._send_ready_message()
            report_time("sent ready")
            self.mainloop()
        except ConnectionError as e:
            self._on_connection_error(e)
        except Exception:
            logger.exception("Exception in MicroPython main method")
            self._report_internal_exception("Internal error")
示例#9
0
if sys.platform == "darwin":
    try:
        os.getcwd()
    except Exception:
        print(
            "\nNB! Potential problems detected, see\nhttps://github.com/thonny/thonny/wiki/MacOSX#catalina\n",
            file=sys.stderr,
        )

if not sys.version_info > (3, 8):
    print(
        "This version of Thonny only supports Python 3.8 and later.\n" +
        "Choose another interpreter from Tools => Options => Interpreter",
        file=sys.stderr,
    )
    sys.exit()
import thonny
from thonny import report_time

report_time("Before importing MainCPythonBackend")
from thonny.plugins.cpython_backend import MainCPythonBackend

thonny.prepare_thonny_user_dir()
thonny.configure_backend_logging()
thonny.set_dpi_aware()

target_cwd = sys.argv[1]
report_time("Before constructing backend")
MainCPythonBackend(target_cwd).mainloop()
示例#10
0
from thonny import launch, report_time

report_time("Before launch")
launch()