Beispiel #1
0
 def load(self):
     """
     Loads a Python file from the file system or extracts a Python sccript
     from a hex file.
     """
     path = self._view.get_load_path(get_workspace_dir())
     logger.info('Loading script from: {}'.format(path))
     try:
         if path.endswith('.py'):
             # Open the file, read the textual content and set the name as
             # the path to the file.
             with open(path, newline='') as f:
                 text = f.read()
             name = path
         else:
             # Open the hex, extract the Python script therein and set the
             # name to None, thus forcing the user to work out what to name
             # the recovered script.
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
             name = None
     except FileNotFoundError:
         pass
     else:
         logger.debug(text)
         self._view.add_tab(name, text)
Beispiel #2
0
 def _load(self, path):
     logger.info('Loading script from: {}'.format(path))
     # see if file is open first
     for widget in self._view.widgets:
         if widget.path is None:  # this widget is an unsaved buffer
             continue
         if path in widget.path:
             logger.info('Script already open.')
             msg = _('The file "{}" is already open.')
             self._view.show_message(msg.format(os.path.basename(path)))
             self._view.focus_tab(widget)
             return
     try:
         if path.endswith('.py'):
             # Open the file, read the textual content and set the name as
             # the path to the file.
             with open(path, newline='') as f:
                 text = f.read()
             name = path
         else:
             # Open the hex, extract the Python script therein and set the
             # name to None, thus forcing the user to work out what to name
             # the recovered script.
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
             name = None
     except FileNotFoundError:
         logger.warning('could not load {}'.format(path))
     else:
         logger.debug(text)
         self._view.add_tab(name, text, self.modes[self.mode].api())
Beispiel #3
0
Datei: logic.py Projekt: ntoll/mu
 def load(self):
     """
     Loads a Python file from the file system or extracts a Python sccript
     from a hex file.
     """
     path = self._view.get_load_path(PYTHON_DIRECTORY)
     logger.info('Loading script from: {}'.format(path))
     try:
         if path.endswith('.py'):
             # Open the file, read the textual content and set the name as
             # the path to the file.
             with open(path, newline='') as f:
                 text = f.read()
             name = path
         else:
             # Open the hex, extract the Python script therein and set the
             # name to None, thus forcing the user to work out what to name
             # the recovered script.
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
             name = None
     except FileNotFoundError:
         pass
     else:
         logger.debug(text)
         self._view.add_tab(name, text)
Beispiel #4
0
 def _load(self, path):
     logger.info('Loading script from: {}'.format(path))
     # see if file is open first
     for widget in self._view.widgets:
         if widget.path is None:  # this widget is an unsaved buffer
             continue
         if path in widget.path:
             logger.info('Script already open.')
             msg = _('The file "{}" is already open.')
             self._view.show_message(msg.format(os.path.basename(path)))
             self._view.focus_tab(widget)
             return
     try:
         if path.endswith('.py'):
             # Open the file, read the textual content and set the name as
             # the path to the file.
             with open(path, newline='') as f:
                 text = f.read()
             name = path
         else:
             # Open the hex, extract the Python script therein and set the
             # name to None, thus forcing the user to work out what to name
             # the recovered script.
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
             name = None
     except (PermissionError, FileNotFoundError):
         logger.warning('could not load {}'.format(path))
     else:
         logger.debug(text)
         self._view.add_tab(name, text, self.modes[self.mode].api())
Beispiel #5
0
 def open_file(self, path):
     """
     Tries to open a MicroPython hex file with an embedded Python script.
     """
     text = None
     if path.lower().endswith('.hex'):
         # Try to open the hex and extract the Python script
         try:
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
         except Exception:
             return None
     return text
Beispiel #6
0
 def open_file(self, path):
     """
     Tries to open a MicroPython hex file with an embedded Python script.
     """
     text = None
     if path.lower().endswith('.hex'):
         # Try to open the hex and extract the Python script
         try:
             with open(path, newline='') as f:
                 text = uflash.extract_script(f.read())
         except Exception:
             return None
     return text
Beispiel #7
0
    def open_file(self, path):
        """
        Tries to open a MicroPython hex file with an embedded Python script.

        Returns the embedded Python script and newline convention.
        """
        text = None
        if path.lower().endswith(".hex"):
            # Try to open the hex and extract the Python script
            try:
                with open(path, newline="") as f:
                    text = uflash.extract_script(f.read())
            except Exception:
                return None, None
            return text, sniff_newline_convention(text)
        else:
            return None, None
Beispiel #8
0
 def load(self):
     """
     Loads a Python file from the file system or extracts a Python sccript
     from a hex file.
     """
     path = self._view.get_load_path(PYTHON_DIRECTORY)
     try:
         if path.endswith('.py'):
             # Open the file, read the textual content and set the name as
             # the path to the file.
             with open(path) as f:
                 text = f.read()
             name = path
         else:
             # Open the hex, extract the Python script therein and set the
             # name to None, thus forcing the user to work out what to name
             # the recovered script.
             with open(path) as f:
                 text = uflash.extract_script(f.read())
             name = None
     except FileNotFoundError:
         pass
     else:
         self._view.add_tab(name, text)
Beispiel #9
0
    def _load(self, path):
        """
        Attempt to load a Python script from the passed in path. This path may
        be a .py file containing Python source code, or a .hex file, created
        for a micro:bit like device, with the source code embedded therein.

        This method will work its way around duplicate paths and also attempt
        to cleanly handle / report / log errors when encountered in a helpful
        manner.
        """
        logger.info('Loading script from: {}'.format(path))
        error = _("The file contains characters Mu expects to be encoded as "
                  "{0} or as the computer's default encoding {1}, but which "
                  "are encoded in some other way.\n\nIf this file was saved "
                  "in another application, re-save the file via the "
                  "'Save as' option and set the encoding to {0}".format(
                      ENCODING, locale.getpreferredencoding()))
        # see if file is open first
        for widget in self._view.widgets:
            if widget.path is None:  # this widget is an unsaved buffer
                continue
            if os.path.samefile(path, widget.path):
                logger.info('Script already open.')
                msg = _('The file "{}" is already open.')
                self._view.show_message(msg.format(os.path.basename(path)))
                self._view.focus_tab(widget)
                return
        try:
            if path.lower().endswith('.py'):
                # Open the file, read the textual content and set the name as
                # the path to the file.
                try:
                    text, newline = read_and_decode(path)
                except UnicodeDecodeError as exc:
                    message = _("Mu cannot read the characters in {}")
                    filename = os.path.basename(path)
                    self._view.show_message(message.format(filename), error)
                    return
                name = path
            elif path.lower().endswith('.hex'):
                # Open the hex, extract the Python script therein and set the
                # name to None, thus forcing the user to work out what to name
                # the recovered script.
                try:
                    with open(path, newline='') as f:
                        text = uflash.extract_script(f.read())
                        newline = sniff_newline_convention(text)
                except Exception:
                    filename = os.path.basename(path)
                    message = _("Unable to load file {}").format(filename)
                    info = _("Mu doesn't understand the hex file and cannot "
                             "extract any Python code. Are you sure this is "
                             "a hex file created with MicroPython?")
                    self._view.show_message(message, info)
                    return
                name = None
            else:
                # Mu won't open other file types, although this may change in
                # the future.
                message = _("Mu only opens .py and .hex files")
                info = _("Currently Mu only works with Python source files or "
                         "hex files created with embedded MicroPython code.")
                self._view.show_message(message, info)
                return
        except OSError:
            message = _("Could not load {}").format(path)
            logger.exception('Could not load {}'.format(path))
            info = _("Does this file exist?\nIf it does, do you have "
                     "permission to read it?\n\nPlease check and try again.")
            self._view.show_message(message, info)
        else:
            logger.debug(text)
            self._view.add_tab(name, text, self.modes[self.mode].api(),
                               newline)
Beispiel #10
0
    def _load(self, path):
        """
        Attempt to load a Python script from the passed in path. This path may
        be a .py file containing Python source code, or a .hex file, created
        for a micro:bit like device, with the source code embedded therein.

        This method will work its way around duplicate paths and also attempt
        to cleanly handle / report / log errors when encountered in a helpful
        manner.
        """
        logger.info('Loading script from: {}'.format(path))
        error = _("The file contains characters Mu expects to be encoded as "
                  "UTF-8, but which are encoded in some other way.\n\nIf this "
                  "file was saved in another application, re-save the file "
                  "via the 'Save as' option and set the encoding to UTF-8.")
        # see if file is open first
        for widget in self._view.widgets:
            if widget.path is None:  # this widget is an unsaved buffer
                continue
            if os.path.samefile(path, widget.path):
                logger.info('Script already open.')
                msg = _('The file "{}" is already open.')
                self._view.show_message(msg.format(os.path.basename(path)))
                self._view.focus_tab(widget)
                return
        try:
            if path.lower().endswith('.py'):
                # Open the file, read the textual content and set the name as
                # the path to the file.
                try:
                    text, newline = read_and_decode(path)
                except UnicodeDecodeError as exc:
                    message = _("Mu cannot read the characters in {}")
                    filename = os.path.basename(path)
                    self._view.show_message(message.format(filename), error)
                    return

                if not ENCODING_COOKIE_RE.match(text):
                    text = ENCODING_COOKIE + NEWLINE + text
                name = path
            elif path.lower().endswith('.hex'):
                # Open the hex, extract the Python script therein and set the
                # name to None, thus forcing the user to work out what to name
                # the recovered script.
                try:
                    with open(path, newline='') as f:
                        text = uflash.extract_script(f.read())
                        newline = sniff_newline_convention(text)
                except Exception:
                    filename = os.path.basename(path)
                    message = _("Unable to load file {}").format(filename)
                    info = _("Mu doesn't understand the hex file and cannot "
                             "extract any Python code. Are you sure this is "
                             "a hex file created with MicroPython?")
                    self._view.show_message(message, info)
                    return
                name = None
            else:
                # Mu won't open other file types, although this may change in
                # the future.
                message = _("Mu only opens .py and .hex files")
                info = _("Currently Mu only works with Python source files or "
                         "hex files created with embedded MicroPython code.")
                self._view.show_message(message, info)
                return
        except (PermissionError, FileNotFoundError):
            message = _("Could not load {}").format(path)
            logger.warning('Could not load {}'.format(path))
            info = _("Does this file exist?\nIf it does, do you have "
                     "permission to read it?\n\nPlease check and try again.")
            self._view.show_message(message, info)
        else:
            logger.debug(text)
            self._view.add_tab(
                name, text, self.modes[self.mode].api(), newline)