Beispiel #1
0
 def create_func(fname):
     """File creation callback"""
     if osp.splitext(fname)[1] in ('.py', '.pyw', '.ipy'):
         create_script(fname)
     else:
         with open(fname, 'wb') as f:
             f.write(to_binary_string(''))
Beispiel #2
0
 def text_changed(self):
     """Text has changed"""
     # Save text as bytes, if it was initially bytes
     if self.is_binary:
         self.text = to_binary_string(self.edit.toPlainText(), 'utf8')
     else:
         self.text = to_text_string(self.edit.toPlainText())
Beispiel #3
0
 def create_new_folder(self, current_path, title, subtitle, is_package):
     """Create new folder"""
     if current_path is None:
         current_path = ''
     if osp.isfile(current_path):
         current_path = osp.dirname(current_path)
     name, valid = QInputDialog.getText(self, title, subtitle,
                                        QLineEdit.Normal, "")
     if valid:
         dirname = osp.join(current_path, to_text_string(name))
         try:
             os.mkdir(dirname)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable "
                                    "to create folder <i>%s</i></b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (dirname, to_text_string(error)))
         finally:
             if is_package:
                 fname = osp.join(dirname, '__init__.py')
                 try:
                     with open(fname, 'wb') as f:
                         f.write(to_binary_string('#'))
                     return dirname
                 except EnvironmentError as error:
                     QMessageBox.critical(self, title,
                                          _("<b>Unable "
                                            "to create file <i>%s</i></b>"
                                            "<br><br>Error message:<br>%s"
                                            ) % (fname,
                                                 to_text_string(error)))
Beispiel #4
0
 def run_command(self, cmd, history=True, new_prompt=True):
     """Run command in interpreter"""
     if not cmd:
         cmd = ''
     else:
         if history:
             self.add_to_history(cmd)
     self.interpreter.stdin_write.write(to_binary_string(cmd + '\n'))
     if not self.multithreaded:
         self.interpreter.run_line()
         self.refresh.emit()
Beispiel #5
0
 def symlink(value, filename):  #analysis:ignore
     newlinkname = filename + "." + unique() + '.newlink'
     newvalname = os.path.join(newlinkname, "symlink")
     os.mkdir(newlinkname)
     f = _open(newvalname, 'wb')
     f.write(to_binary_string(value))
     f.flush()
     f.close()
     try:
         rename(newlinkname, filename)
     except:
         os.remove(newvalname)
         os.rmdir(newlinkname)
         raise
Beispiel #6
0
def check_with_pyflakes(source_code, filename=None):
    """Check source code with pyflakes
    Returns an empty list if pyflakes is not installed"""
    try:
        if filename is None:
            filename = '<string>'
        try:
            source_code += '\n'
        except TypeError:
            # Python 3
            source_code += to_binary_string('\n')

        import _ast
        from pyflakes.checker import Checker
        # First, compile into an AST and handle syntax errors.
        try:
            tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST)
        except SyntaxError as value:
            # If there's an encoding problem with the file, the text is None.
            if value.text is None:
                results = []
            else:
                results = [(value.args[0], value.lineno)]
        except (ValueError, TypeError):
            # Example of ValueError: file contains invalid \x escape character
            # (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)
            # Example of TypeError: file contains null character
            # (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)
            results = []
        else:
            # Okay, it's syntactically valid.  Now check it.
            w = Checker(tree, filename)
            w.messages.sort(key=lambda x: x.lineno)
            results = []
            coding = encoding.get_coding(source_code)
            lines = source_code.splitlines()
            for warning in w.messages:
                if 'analysis:ignore' not in \
                   to_text_string(lines[warning.lineno-1], coding):
                    results.append((warning.message % warning.message_args,
                                    warning.lineno))
    except Exception:
        # Never return None to avoid lock in trex/widgets/editor.py
        # See Issue 1547
        results = []
        if DEBUG_EDITOR:
            traceback.print_exc()  # Print exception in internal console
    return results
Beispiel #7
0
def display_to_value(value, default_value, ignore_errors=True):
    """Convert back to value"""
    from qtpy.compat import from_qvariant
    value = from_qvariant(value, to_text_string)
    try:
        np_dtype = get_numpy_dtype(default_value)
        if isinstance(default_value, bool):
            # We must test for boolean before NumPy data types
            # because `bool` class derives from `int` class
            try:
                value = bool(float(value))
            except ValueError:
                value = value.lower() == "true"
        elif np_dtype is not None:
            if 'complex' in str(type(default_value)):
                value = np_dtype(complex(value))
            else:
                value = np_dtype(value)
        elif is_binary_string(default_value):
            value = to_binary_string(value, 'utf8')
        elif is_text_string(default_value):
            value = to_text_string(value)
        elif isinstance(default_value, complex):
            value = complex(value)
        elif isinstance(default_value, float):
            value = float(value)
        elif isinstance(default_value, int):
            try:
                value = int(value)
            except ValueError:
                value = float(value)
        elif isinstance(default_value, datetime.datetime):
            value = datestr_to_datetime(value)
        elif isinstance(default_value, datetime.date):
            value = datestr_to_datetime(value).date()
        elif ignore_errors:
            value = try_to_eval(value)
        else:
            value = eval(value)
    except (ValueError, SyntaxError):
        if ignore_errors:
            value = try_to_eval(value)
        else:
            return default_value
    return value
Beispiel #8
0
    def setData(self, index, value, role=Qt.EditRole):
        """Cell content change"""
        if not index.isValid() or self.readonly:
            return False
        i = index.row()
        j = index.column()
        value = from_qvariant(value, str)
        dtype = self._data.dtype.name
        if dtype == "bool":
            try:
                val = bool(float(value))
            except ValueError:
                val = value.lower() == "true"
        elif dtype.startswith("string") or dtype.startswith("bytes"):
            val = to_binary_string(value, 'utf8')
        elif dtype.startswith("unicode") or dtype.startswith("str"):
            val = to_text_string(value)
        else:
            if value.lower().startswith('e') or value.lower().endswith('e'):
                return False
            try:
                val = complex(value)
                if not val.imag:
                    val = val.real
            except ValueError as e:
                QMessageBox.critical(self.dialog, "Error",
                                     "Value error: %s" % str(e))
                return False
        try:
            self.test_array[0] = val  # will raise an Exception eventually
        except OverflowError as e:
            print(type(e.message))  # trex: test-skip
            QMessageBox.critical(self.dialog, "Error",
                                 "Overflow error: %s" % e.message)
            return False

        # Add change to self.changes
        self.changes[(i, j)] = val
        self.dataChanged.emit(index, index)
        if not is_string(val):
            if val > self.vmax:
                self.vmax = val
            if val < self.vmin:
                self.vmin = val
        return True
Beispiel #9
0
    def send_to_process(self, text):
        if not self.is_running():
            return
        if not is_text_string(text):
            text = to_text_string(text)
        if self.mpl_backend == 0 and os.name == 'nt' and \
          self.introspection_socket is not None:
            communicate(self.introspection_socket,
                        "toggle_inputhook_flag(True)")
#            # Socket-based alternative (see input hook in sitecustomize.py):
#            while self.local_server.hasPendingConnections():
#                self.local_server.nextPendingConnection().write('go!')
        if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \
          any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]):
            text = 'evalsc(r"%s")\n' % text
        if not text.endswith('\n'):
            text += '\n'
        self.process.write(to_binary_string(text, 'utf8'))
        self.process.waitForBytesWritten(-1)

        # Eventually write prompt faster (when hitting Enter continuously)
        # -- necessary/working on Windows only:
        if os.name == 'nt':
            self.write_error()
Beispiel #10
0
 def exit_interpreter(self):
     """Exit interpreter"""
     self.interpreter.exit_flag = True
     if self.multithreaded:
         self.interpreter.stdin_write.write(to_binary_string('\n'))
     self.interpreter.restore_stds()