INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Loads the last visible toolbars from the. ini file.
def load_last_visible_toolbars(self): """Loads the last visible toolbars from the .ini file.""" toolbars_names = CONF.get('main', 'last_visible_toolbars', default=[]) if toolbars_names: dic = {} for toolbar in self.toolbarslist: dic[toolbar.objectN...
Show/ Hides toolbars.
def show_toolbars(self): """Show/Hides toolbars.""" value = not self.toolbars_visible CONF.set('main', 'toolbars_visible', value) if value: self.save_visible_toolbars() else: self.get_visible_toolbars() for toolbar in self.visible_toolbar...
Handle an invalid active project.
def valid_project(self): """Handle an invalid active project.""" try: path = self.projects.get_active_project_path() except AttributeError: return if bool(path): if not self.projects.is_valid_project(path): if path: ...
Show action shortcuts in menu
def show_shortcuts(self, menu): """Show action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setShortcut(element._shown_shortcut)
Hide action shortcuts in menu
def hide_shortcuts(self, menu): """Hide action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setShortcut(QKeySequence())
Get properties of focus widget Returns tuple ( widget properties ) where properties is a tuple of booleans: ( is_console not_readonly readwrite_editor )
def get_focus_widget_properties(self): """Get properties of focus widget Returns tuple (widget, properties) where properties is a tuple of booleans: (is_console, not_readonly, readwrite_editor)""" from spyder.plugins.editor.widgets.editor import TextEditBaseWidget from spyde...
Update edit menu
def update_edit_menu(self): """Update edit menu""" widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return # !!! Below this line, widget is expected to be a QPlainTextEdit # in...
Update search menu
def update_search_menu(self): """Update search menu""" # Disabling all actions except the last one # (which is Find in files) to begin with for child in self.search_menu.actions()[:-1]: child.setEnabled(False) widget, textedit_properties = self.get_focus_widge...
Set splash message
def set_splash(self, message): """Set splash message""" if self.splash is None: return if message: logger.info(message) self.splash.show() self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAb...
closeEvent reimplementation
def closeEvent(self, event): """closeEvent reimplementation""" if self.closing(True): event.accept() else: event.ignore()
Reimplement Qt method
def resizeEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_size = self.size() QMainWindow.resizeEvent(self, event) # To be used by the tour to be able to resize self.sig_resized.emit(event)
Reimplement Qt method
def moveEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_position = self.pos() QMainWindow.moveEvent(self, event) # To be used by the tour to be able to move self.sig_moved.emit(event)
Reimplement Qt method
def hideEvent(self, event): """Reimplement Qt method""" try: for plugin in (self.widgetlist + self.thirdparty_plugins): if plugin.isAncestorOf(self.last_focused_widget): plugin.visibility_changed(True) QMainWindow.hideEvent(self, event) ...
To keep track of to the last focused widget
def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is no...
Exit tasks
def closing(self, cancelable=False): """Exit tasks""" if self.already_closed or self.is_starting_up: return True if cancelable and CONF.get('main', 'prompt_on_exit'): reply = QMessageBox.critical(self, 'Spyder', 'Do you reall...
Add QDockWidget and toggleViewAction
def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| QDockWidget.DockWid...
Lock/ Unlock dockwidgets and toolbars
def toggle_lock(self, value): """Lock/Unlock dockwidgets and toolbars""" self.interface_locked = value CONF.set('main', 'panes_locked', value) # Apply lock to panes for plugin in (self.widgetlist + self.thirdparty_plugins): if self.interface_locked: ...
Shortcut: Ctrl + Alt + Shift + M First call: maximize current dockwidget Second call ( or restore = True ): restore original window layout
def maximize_dockwidget(self, restore=False): """Shortcut: Ctrl+Alt+Shift+M First call: maximize current dockwidget Second call (or restore=True): restore original window layout""" if self.state_before_maximizing is None: if restore: return ...
Add widget actions to toolbar
def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
Create About Spyder dialog with general information.
def about(self): """Create About Spyder dialog with general information.""" versions = get_versions() # Show Git revision for development version revlink = '' if versions['revision']: rev = versions['revision'] revlink = " (<a href='https://github.c...
Show Spyder s Dependencies dialog box
def show_dependencies(self): """Show Spyder's Dependencies dialog box""" from spyder.widgets.dependencies import DependenciesDialog dlg = DependenciesDialog(self) dlg.set_data(dependencies.DEPENDENCIES) dlg.exec_()
Render issue before sending it to Github
def render_issue(self, description='', traceback=''): """Render issue before sending it to Github""" # Get component versions versions = get_versions() # Get git revision for development version revision = '' if versions['revision']: revision = versio...
Report a Spyder issue to github generating body text if needed.
def report_issue(self, body=None, title=None, open_webpage=False): """Report a Spyder issue to github, generating body text if needed.""" if body is None: from spyder.widgets.reporterror import SpyderErrorDialog report_dlg = SpyderErrorDialog(self, is_report=True) ...
Global callback
def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = from_qvariant(action.data(), to_text_string) from spyder.plugins.editor.widgets.editor import TextEditBaseWidget from spyder.plugins.ipythonconsole...
Open external console
def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: if CONF.get('main...
Execute lines in IPython console and eventually set focus to the Editor.
def execute_in_external_console(self, lines, focus_to_editor): """ Execute lines in IPython console and eventually set focus to the Editor. """ console = self.ipyconsole console.switch_to_plugin() console.execute_code(lines) if focus_to_editor: ...
Open filename with the appropriate application Redirect to the right widget ( txt - > editor spydata - > workspace... ) or open file outside Spyder ( if extension is not supported )
def open_file(self, fname, external=False): """ Open filename with the appropriate application Redirect to the right widget (txt -> editor, spydata -> workspace, ...) or open file outside Spyder (if extension is not supported) """ fname = to_text_string(fname) ...
Open external files that can be handled either by the Editor or the variable explorer inside Spyder.
def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ fname = encoding.to_unicode_from_fs(fname) if osp.isfile(fname): self.open_file(fname, external=True) ...
Return Spyder PYTHONPATH
def get_spyder_pythonpath(self): """Return Spyder PYTHONPATH""" active_path = [p for p in self.path if p not in self.not_active_path] return active_path + self.project_path
Add Spyder path to sys. path
def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path)
Remove Spyder path from sys. path
def remove_path_from_sys_path(self): """Remove Spyder path from sys.path""" for path in self.path + self.project_path: while path in sys.path: sys.path.remove(path)
Spyder path manager
def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self...
Projects PYTHONPATH contribution has changed
def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed""" self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit()
Apply settings changed in Preferences dialog box
def apply_settings(self): """Apply settings changed in 'Preferences' dialog box""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: ...
Update dockwidgets features settings
def apply_panes_settings(self): """Update dockwidgets features settings""" for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): features = features | QDockWidget.DockWidget...
Update status bar widgets settings
def apply_statusbar_settings(self): """Update status bar widgets settings""" show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status, 'memory_usage'), ...
Edit Spyder preferences
def edit_preferences(self): """Edit Spyder preferences""" from spyder.preferences.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(self.prefs_dialog_size) ...
Register QAction or QShortcut to Spyder main application with shortcut ( context name default )
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application, with shortcut (context, name, default) """ self.shortcut_data.append( (qaction_or_qshortcut, contex...
Apply shortcuts settings to all widgets/ plugins
def apply_shortcuts(self): """Apply shortcuts settings to all widgets/plugins""" toberemoved = [] for index, (qobject, context, name, add_sc_to_tip) in enumerate(self.shortcut_data): keyseq = QKeySequence( get_shortcut(context, name) ) try: ...
Quit and reset Spyder and then Restart application.
def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Ye...
Quit and Restart Spyder application. If reset True it allows to reset spyder on restart.
def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_...
Show interactive tour.
def show_tour(self, index): """Show interactive tour.""" self.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour()
Open file list management dialog box.
def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: ...
Add a plugin to the File Switcher.
def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher.""" if self.fileswitcher is None: from spyder.widgets.fileswitcher import FileSwitcher self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon) else: se...
Called by WorkerUpdates when ready
def _check_updates_ready(self): """Called by WorkerUpdates when ready""" from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after startup (when using the # me...
Check for spyder updates on github releases using a QThread.
def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """ from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) ...
Private set method
def _set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print('%s[ %s ] = %s' % (...
Save config into the associated. ini file
def _save(self): """ Save config into the associated .ini file """ # See Issue 1086 and 1242 for background on why this # method contains all the exception handling. fname = self.filename() def _write_file(fname): if PY2: # P...
Defines the name of the configuration file to use.
def filename(self): """Defines the name of the configuration file to use.""" # Needs to be done this way to be used by the project config. # To fix on a later PR self._filename = getattr(self, '_filename', None) self._root_path = getattr(self, '_root_path', None) ...
Create a. ini filename located in user home directory. This. ini files stores the global spyder preferences.
def _filename_global(self): """Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. """ if self.subfolder is None: config_file = osp.join(get_home_dir(), '.%s.ini' % self.name) return config_file ...
Set configuration ( not application! ) version
def set_version(self, version='0.0.0', save=True): """Set configuration (not application!) version""" self.set(self.DEFAULT_SECTION_NAME, 'version', version, save=save)
Load config from the associated. ini file
def load_from_ini(self): """ Load config from the associated .ini file """ try: if PY2: # Python 2 fname = self.filename() if osp.isfile(fname): try: with codecs.open(fname, ...
Read old defaults
def _load_old_defaults(self, old_version): """Read old defaults""" old_defaults = cp.ConfigParser() if check_version(old_version, '3.0.0', '<='): path = get_module_source_path('spyder') else: path = osp.dirname(self.filename()) path = osp.join(path,...
Save new defaults
def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults""" new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defaults.set_defaults(de...
Update defaults after a change in version
def _update_defaults(self, defaults, old_version, verbose=False): """Update defaults after a change in version""" old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: new_value = options[ option ] ...
Remove options which are present in the. ini file but not in defaults
def _remove_deprecated_options(self, old_version): """ Remove options which are present in the .ini file but not in defaults """ old_defaults = self._load_old_defaults(old_version) for section in old_defaults.sections(): for option, _ in old_defaults.items(secti...
Set defaults from the current config
def set_as_defaults(self): """ Set defaults from the current config """ self.defaults = [] for section in self.sections(): secdict = {} for option, value in self.items(section, raw=self.raw): secdict[option] = value sel...
Reset config to Default values
def reset_to_defaults(self, save=True, verbose=False, section=None): """ Reset config to Default values """ for sec, options in self.defaults: if section == None or section == sec: for option in options: value = options[ option ] ...
Private method to check section and option types
def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a str...
Get Default value for a given ( section option ) - > useful for type checking in get method
def get_default(self, section, option): """ Get Default value for a given (section, option) -> useful for type checking in 'get' method """ section = self._check_section_option(section, option) for sec, options in self.defaults: if sec == section: ...
Get an option section = None: attribute a default section name default: default value ( if not specified an exception will be raised if option doesn t exist )
def get(self, section, option, default=NoDefault): """ Get an option section=None: attribute a default section name default: default value (if not specified, an exception will be raised if option doesn't exist) """ section = self._check_section_option(secti...
Set Default value for a given ( section option ) - > called when a new ( section option ) is set and no default exists
def set_default(self, section, option, default_value): """ Set Default value for a given (section, option) -> called when a new (section, option) is set and no default exists """ section = self._check_section_option(section, option) for sec, options in self.defaults...
Set an option section = None: attribute a default section name
def set(self, section, option, value, verbose=False, save=True): """ Set an option section=None: attribute a default section name """ section = self._check_section_option(section, option) default_value = self.get_default(section, option) if default_value is...
Return temporary Spyder directory checking previously that it exists.
def get_temp_dir(suffix=None): """ Return temporary Spyder directory, checking previously that it exists. """ to_join = [tempfile.gettempdir()] if os.name == 'nt': to_join.append('spyder') else: username = encoding.to_unicode_from_fs(getuser()) to_join.append('...
Return program absolute path if installed in PATH. Otherwise return None
def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath
Find program in PATH and return absolute path Try adding. exe or. bat to basename on Windows platforms ( return None if not found )
def find_program(basename): """ Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not found) """ names = [basename] if os.name == 'nt': # Windows platforms extensions = ('.exe', '.bat', '.cmd') ...
Given a dict populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example close_fds is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the modified dict.
def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. ...
Execute the given shell command. Note that * args and ** kwargs will be passed to the subprocess call. If shell is given in subprocess_kwargs it must be True otherwise ProgramError will be raised.. If executable is not given in subprocess_kwargs it will be set to the value of the SHELL environment variable. Note that s...
def run_shell_command(cmdstr, **subprocess_kwargs): """ Execute the given shell command. Note that *args and **kwargs will be passed to the subprocess call. If 'shell' is given in subprocess_kwargs it must be True, otherwise ProgramError will be raised. . If 'executable' is no...
Run program in a separate process. NOTE: returns the process object created by subprocess. Popen (). This can be used with proc. communicate () for example. If shell appears in the kwargs it must be False otherwise ProgramError will be raised. If only the program name is given and not the full path a lookup will be per...
def run_program(program, args=None, **subprocess_kwargs): """ Run program in a separate process. NOTE: returns the process object created by `subprocess.Popen()`. This can be used with `proc.communicate()` for example. If 'shell' appears in the kwargs, it must be False, otherwise ...
Generalized os. startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices. openUrl Returns True if successfull otherwise returns False.
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices ...
Return absolute path if Python script exists ( otherwise return None ) package = None - > module is in sys. path ( standard library modules )
def python_script_exists(package=None, module=None): """ Return absolute path if Python script exists (otherwise, return None) package=None -> module is in sys.path (standard library modules) """ assert module is not None try: if package is None: path = imp.find_modul...
Run Python script in a separate process package = None - > module is in sys. path ( standard library modules )
def run_python_script(package=None, module=None, args=[], p_args=[]): """ Run Python script in a separate process package=None -> module is in sys.path (standard library modules) """ assert module is not None assert isinstance(args, (tuple, list)) and isinstance(p_args, (tuple, list)) ...
Split the string text using shell - like syntax This avoids breaking single/ double - quoted strings ( e. g. containing strings with spaces ). This function is almost equivalent to the shlex. split function ( see standard library shlex ) except that it is supporting unicode strings ( shlex does not support unicode unti...
def shell_split(text): """ Split the string `text` using shell-like syntax This avoids breaking single/double-quoted strings (e.g. containing strings with spaces). This function is almost equivalent to the shlex.split function (see standard library `shlex`) except that it is supporting u...
Construct Python interpreter arguments
def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments""" p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_args.extend(['-m', 'pdb']) if fname...
Run Python script in an external system terminal.: str wdir: working directory may be empty.
def run_python_script_in_terminal(fname, wdir, args, interact, debug, python_args, executable=None): """ Run Python script in an external system terminal. :str wdir: working directory, may be empty. """ if executable is None: executable = get_python...
Check version string of an active module against a required version. If dev/ prerelease tags result in TypeError for string - number comparison it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. Copyright ( C ) 2013 The IPython Development Te...
def check_version(actver, version, cmp_op): """ Check version string of an active module against a required version. If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their...
Return True if module * module_name * is installed If version is not None checking module version ( module must have an attribute named __version__ ) version may starts with = > = > or < to specify the exact requirement ; multiple conditions may be separated by ; ( e. g. > = 0. 13 ; <1. 0 ) interpreter: check if a modu...
def is_module_installed(module_name, version=None, installed_version=None, interpreter=None): """ Return True if module *module_name* is installed If version is not None, checking module version (module must have an attribute named '__version__') version may starts ...
Check that the python interpreter file has a valid name.
def is_python_interpreter_valid_name(filename): """Check that the python interpreter file has a valid name.""" pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
Evaluate wether a file is a python interpreter or not.
def is_python_interpreter(filename): """Evaluate wether a file is a python interpreter or not.""" real_filename = os.path.realpath(filename) # To follow symlink if existent if (not osp.isfile(real_filename) or not is_python_interpreter_valid_name(filename)): return False elif is_...
Check that the python interpreter has pythonw.
def is_pythonw(filename): """Check that the python interpreter has 'pythonw'.""" pattern = r'.*python(\d\.?\d*)?w(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
Check that the python interpreter can execute help.
def check_python_help(filename): """Check that the python interpreter can execute help.""" try: proc = run_program(filename, ["-h"]) output = to_text_string(proc.communicate()[0]) valid = ("Options and arguments (and corresponding environment " "variables)") ...
Override Qt method.
def sizeHint(self): """Override Qt method. Returns the widget size hint (based on the editor font size). """ fm = QFontMetrics(self.editor.font()) size_hint = QSize(fm.height(), fm.height()) if size_hint.width() > 16: size_hint.setWidth(16) return siz...
Draw the given breakpoint pixmap.
def _draw_breakpoint_icon(self, top, painter, icon_name): """Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. painter (QPainter) icon_name (srt): key of icon to draw (see: self.icons) """ rect = QRect(0, ...
Override Qt method.
def paintEvent(self, event): """Override Qt method. Paint breakpoints icons. """ super(DebuggerPanel, self).paintEvent(event) painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) for top, line_number, block in self.editor.visible_...
Override Qt method
def mousePressEvent(self, event): """Override Qt method Add/remove breakpoints by single click. """ line_number = self.editor.get_linenumber_from_mouse_event(event) shift = event.modifiers() & Qt.ShiftModifier self.editor.debugger.toogle_breakpoint(line_number, ...
Override Qt method.
def mouseMoveEvent(self, event): """Override Qt method. Draw semitransparent breakpoint hint. """ self.line_number_hint = self.editor.get_linenumber_from_mouse_event( event) self.update()
Change visibility and connect/ disconnect signal.
def on_state_changed(self, state): """Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate. """ if state: self.editor.sig_breakpoints_changed.connect(self.repaint) self.editor.sig_debug_stop.connect(self.set_current...
Qt/ Python2/ 3 compatibility helper.
def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
This methods illustrates how the workers can be used.
def sleeping_func(arg, secs=10, result_queue=None): """This methods illustrates how the workers can be used.""" import time time.sleep(secs) if result_queue is not None: result_queue.put(arg) else: return arg
Start the worker ( emits sig_started signal with worker as arg ).
def start(self): """Start the worker (emits sig_started signal with worker as arg).""" if not self._started: self.sig_started.emit(self) self._started = True
Start process worker for given method args and kwargs.
def _start(self): """Start process worker for given method args and kwargs.""" error = None output = None try: output = self.func(*self.args, **self.kwargs) except Exception as err: error = err if not self._is_finished: self.sig_finis...
Return the encoding/ codepage to use.
def _get_encoding(self): """Return the encoding/codepage to use.""" enco = 'utf-8' # Currently only cp1252 is allowed? if WIN: import ctypes codepage = to_text_string(ctypes.cdll.kernel32.GetACP()) # import locale # locale.getpreferredenc...
Set the environment on the QProcess.
def _set_environment(self, environ): """Set the environment on the QProcess.""" if environ: q_environ = self._process.processEnvironment() for k, v in environ.items(): q_environ.insert(k, v) self._process.setProcessEnvironment(q_environ)
Callback for partial output.
def _partial(self): """Callback for partial output.""" raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, self._get_encoding()) if self._partial_stdout is None: self._partial_stdout = stdout else: self._partial_stdou...
Callback for communicate.
def _communicate(self): """Callback for communicate.""" if (not self._communicate_first and self._process.state() == QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
Retrieve information.
def communicate(self): """Retrieve information.""" self._communicate_first = True self._process.waitForFinished() enco = self._get_encoding() if self._partial_stdout is None: raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(ra...
Start process.
def _start(self): """Start process.""" if not self._fired: self._partial_ouput = None self._process.start(self._cmd_list[0], self._cmd_list[1:]) self._timer.start()
Terminate running processes.
def terminate(self): """Terminate running processes.""" if self._process.state() == QProcess.Running: try: self._process.terminate() except Exception: pass self._fired = True
Delete periodically workers in workers bag.
def _clean_workers(self): """Delete periodically workers in workers bag.""" while self._bag_collector: self._bag_collector.popleft() self._timer_worker_delete.stop()
Start threads and check for inactive workers.
def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Thre...