Dataset Viewer
code
stringlengths 9
189k
| meta_data.file_name
stringclasses 538
values | meta_data.module
stringclasses 202
values | meta_data.contains_class
bool 2
classes | meta_data.contains_function
bool 2
classes | meta_data.file_imports
sequencelengths 0
97
| meta_data.start_line
int64 -1
6.71k
| meta_data.end_line
int64 -1
6.74k
|
---|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Script for running Spyder tests programmatically.
"""
# Standard library imports
import argparse
import os
# To activate/deactivate certain things for pytests only
# NOTE: Please leave this before any other import here!!
os.environ['SPYDER_PYTEST'] = 'True'
# Third party imports
# NOTE: This needs to be imported before any QApplication.
# Don't remove it or change it to a different location!
# pylint: disable=wrong-import-position
from qtpy import QtWebEngineWidgets # noqa
import pytest
# To run our slow tests only in our CIs
CI = bool(os.environ.get('CI', None))
RUN_SLOW = os.environ.get('RUN_SLOW', None) == 'true' | runtests.py | spyder | false | false | [
"import argparse",
"import os",
"from qtpy import QtWebEngineWidgets # noqa",
"import pytest"
] | 1 | 29 |
def run_pytest(run_slow=False, extra_args=None):
"""Run pytest tests for Spyder."""
# Be sure to ignore subrepos
pytest_args = ['-vv', '-rw', '--durations=10', '--ignore=./external-deps',
'-W ignore::UserWarning', '--timeout=120']
if CI:
# Show coverage
pytest_args += ['--cov=spyder', '--no-cov-on-fail', '--cov-report=xml']
# To display nice tests resume in Azure's web page
if os.environ.get('AZURE', None) is not None:
pytest_args += ['--cache-clear', '--junitxml=result.xml']
if run_slow or RUN_SLOW:
pytest_args += ['--run-slow']
# Allow user to pass a custom test path to pytest to e.g. run just one test
if extra_args:
pytest_args += extra_args
print("Pytest Arguments: " + str(pytest_args))
errno = pytest.main(pytest_args)
# sys.exit doesn't work here because some things could be running in the
# background (e.g. closing the main window) when this point is reached.
# If that's the case, sys.exit doesn't stop the script as you would expect.
if errno != 0:
raise SystemExit(errno) | runtests.py | spyder | false | true | [
"import argparse",
"import os",
"from qtpy import QtWebEngineWidgets # noqa",
"import pytest"
] | 32 | 58 |
def main():
"""Parse args then run the pytest suite for Spyder."""
test_parser = argparse.ArgumentParser(
usage='python runtests.py [-h] [--run-slow] [pytest_args]',
description="Helper script to run Spyder's test suite")
test_parser.add_argument('--run-slow', action='store_true', default=False,
help='Run the slow tests')
test_args, pytest_args = test_parser.parse_known_args()
run_pytest(run_slow=test_args.run_slow, extra_args=pytest_args)
if __name__ == '__main__':
main() | runtests.py | spyder | false | true | [
"import argparse",
"import os",
"from qtpy import QtWebEngineWidgets # noqa",
"import pytest"
] | 61 | 73 |
#!/usr/bin/env python3
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Helper script for installing spyder and external-deps locally in editable mode.
"""
import argparse
import os
import sys
from logging import Formatter, StreamHandler, getLogger
from pathlib import Path
from subprocess import check_output
from importlib_metadata import PackageNotFoundError, distribution
from packaging.requirements import Requirement
# Remove current/script directory from sys.path[0] if added by the Python invocation,
# otherwise Spyder's install status may be incorrectly determined.
SYS_PATH_0 = Path(sys.path[0]).resolve()
if SYS_PATH_0 in (Path(__file__).resolve().parent, Path.cwd()):
sys.path.pop(0)
DEVPATH = Path(__file__).resolve().parent
DEPS_PATH = DEVPATH / 'external-deps'
BASE_COMMAND = [sys.executable, '-m', 'pip', 'install', '--no-deps']
REPOS = {}
for p in [DEVPATH] + list(DEPS_PATH.iterdir()):
if (
p.name.startswith('.')
or not p.is_dir()
and not ((p / 'setup.py').exists() or (p / 'pyproject.toml').exists())
):
continue
try:
dist = distribution(p.name)
except PackageNotFoundError:
dist = None
editable = None
else:
editable = (p == dist._path or p in dist._path.parents) | install_dev_repos.py | spyder | false | false | [
"import argparse",
"import os",
"import sys",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_output",
"from importlib_metadata import PackageNotFoundError, distribution",
"from packaging.requirements import Requirement"
] | 1 | 46 |
try:
dist = distribution(p.name)
except PackageNotFoundError:
dist = None
editable = None
else:
editable = (p == dist._path or p in dist._path.parents)
# This fixes detecting that PyLSP was installed in editable mode under
# some scenarios.
# Fixes spyder-ide/spyder#19712
if p.name == 'python-lsp-server':
for f in dist.files:
if 'editable' in f.name:
editable = True
break
REPOS[p.name] = {'repo': p, 'dist': dist, 'editable': editable}
# ---- Setup logger
fmt = Formatter('%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s')
h = StreamHandler()
h.setFormatter(fmt)
logger = getLogger('InstallDevRepos')
logger.addHandler(h)
logger.setLevel('INFO') | install_dev_repos.py | spyder | false | false | [
"import argparse",
"import os",
"import sys",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_output",
"from importlib_metadata import PackageNotFoundError, distribution",
"from packaging.requirements import Requirement"
] | 40 | 65 |
def get_python_lsp_version():
"""Get current version to pass it to setuptools-scm."""
req_file = DEVPATH / 'requirements' / 'main.yml'
with open(req_file, 'r', encoding='utf-8') as f:
for line in f:
if 'python-lsp-server' not in line:
continue
line = line.split('-')[-1]
specifiers = Requirement(line).specifier
break
else:
return "0.0.0"
for specifier in specifiers:
if "=" in specifier.operator:
return specifier.version
else:
return "0.0.0" | install_dev_repos.py | spyder | false | true | [
"import argparse",
"import os",
"import sys",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_output",
"from importlib_metadata import PackageNotFoundError, distribution",
"from packaging.requirements import Requirement"
] | 68 | 85 |
def install_repo(name, not_editable=False):
"""
Install a single repo from source located in spyder/external-deps, ignoring
dependencies, in standard or editable mode.
Parameters
----------
name : str
Must be 'spyder' or the distribution name of a repo in
spyder/external-deps.
not_editable : bool (False)
Install repo in standard mode (True) or editable mode (False).
Editable mode uses pip's `-e` flag.
"""
try:
repo_path = REPOS[name]['repo']
except KeyError:
logger.warning('Distribution %r not valid. Must be one of %s',
name, set(REPOS.keys()))
return
install_cmd = BASE_COMMAND.copy()
# PyLSP requires pretend version
env = None
if name == 'python-lsp-server':
env = {**os.environ}
env.update(
{'SETUPTOOLS_SCM_PRETEND_VERSION': get_python_lsp_version()})
if not_editable:
mode = 'standard'
else:
# Add edit flag to install command
install_cmd.append('-e')
mode = 'editable'
logger.info('Installing %r from source in %s mode.', name, mode)
install_cmd.append(repo_path.as_posix())
check_output(install_cmd, env=env) | install_dev_repos.py | spyder | false | true | [
"import argparse",
"import os",
"import sys",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_output",
"from importlib_metadata import PackageNotFoundError, distribution",
"from packaging.requirements import Requirement"
] | 88 | 128 |
def main(install=tuple(REPOS.keys()), no_install=tuple(), **kwargs):
"""
Install all subrepos from source.
Parameters
----------
install : iterable (spyder and all repos in spyder/external-deps)
Distribution names of repos to be installed from spyder/external-deps.
no_install : iterable ()
Distribution names to exclude from install.
**kwargs :
Keyword arguments passed to `install_repo`.
"""
_install = set(install) - set(no_install)
for repo in _install:
install_repo(repo, **kwargs)
if __name__ == '__main__':
# ---- Parse command line
parser = argparse.ArgumentParser(
usage="python install_dev_repos.py [options]")
parser.add_argument(
'--install', nargs='+',
default=REPOS.keys(),
help="Space-separated list of distribution names to install, e.g. "
"qtconsole spyder-kernels. If option not provided, then all of "
"the repos in spyder/external-deps are installed"
)
parser.add_argument(
'--no-install', nargs='+', default=[],
help="Space-separated list of distribution names to exclude from "
"install. Default is empty list."
)
parser.add_argument(
'--not-editable', action='store_true', default=False,
help="Install in standard mode, not editable mode."
)
args = parser.parse_args()
# ---- Install repos locally
main(**vars(args)) | install_dev_repos.py | spyder | false | true | [
"import argparse",
"import os",
"import sys",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_output",
"from importlib_metadata import PackageNotFoundError, distribution",
"from packaging.requirements import Requirement"
] | 131 | 174 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Spyder
======
The Scientific Python Development Environment
Spyder is a powerful scientific environment written in Python, for Python,
and designed by and for scientists, engineers and data analysts.
It features a unique combination of the advanced editing, analysis, debugging
and profiling functionality of a comprehensive development tool with the data
exploration, interactive execution, deep inspection and beautiful visualization
capabilities of a scientific package.
"""
from __future__ import print_function
# Standard library imports
from distutils.command.install_data import install_data
import io
import os
import os.path as osp
import subprocess
import sys
# Third party imports
from setuptools import setup, find_packages
from setuptools.command.install import install
# =============================================================================
# Minimal Python version sanity check
# Taken from the notebook setup.py -- Modified BSD License
# =============================================================================
v = sys.version_info
if v[0] >= 3 and v[:2] < (3, 8):
error = "ERROR: Spyder requires Python version 3.8 and above."
print(error, file=sys.stderr)
sys.exit(1) | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 1 | 45 |
# =============================================================================
# Constants
# =============================================================================
NAME = 'spyder'
LIBNAME = 'spyder'
WINDOWS_INSTALLER_NAME = os.environ.get('EXE_NAME')
from spyder import __version__, __website_url__ #analysis:ignore
# =============================================================================
# Auxiliary functions
# ============================================================================= | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 48 | 60 |
def get_package_data(name, extlist):
"""
Return data files for package *name* with extensions in *extlist*.
"""
flist = []
# Workaround to replace os.path.relpath (not available until Python 2.6):
offset = len(name)+len(os.pathsep)
for dirpath, _dirnames, filenames in os.walk(name):
if 'tests' not in dirpath:
for fname in filenames:
if (not fname.startswith('.') and
osp.splitext(fname)[1] in extlist):
flist.append(osp.join(dirpath, fname)[offset:])
return flist
def get_subpackages(name):
"""
Return subpackages of package *name*.
"""
splist = []
for dirpath, _dirnames, _filenames in os.walk(name):
if 'tests' not in dirpath:
if osp.isfile(osp.join(dirpath, '__init__.py')):
splist.append(".".join(dirpath.split(os.sep)))
return splist
def get_data_files():
"""
Return data_files in a platform dependent manner.
"""
if sys.platform.startswith('linux'):
data_files = [('share/applications', ['scripts/spyder.desktop']),
('share/icons', ['img_src/spyder.png']),
('share/metainfo',
['scripts/org.spyder_ide.spyder.appdata.xml'])]
elif os.name == 'nt':
data_files = [('scripts', ['img_src/spyder.ico'])]
else:
data_files = []
return data_files | setup.py | spyder | false | true | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 61 | 104 |
def get_packages():
"""
Return package list.
"""
packages = get_subpackages(LIBNAME)
return packages
# =============================================================================
# Make Linux detect Spyder desktop file (will not work with wheels)
# ============================================================================= | setup.py | spyder | false | true | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 107 | 117 |
class CustomInstallData(install_data):
def run(self):
install_data.run(self)
if sys.platform.startswith('linux'):
try:
subprocess.call(['update-desktop-database'])
except:
print("ERROR: unable to update desktop database",
file=sys.stderr)
CMDCLASS = {'install_data': CustomInstallData}
# =============================================================================
# Main scripts
# =============================================================================
# NOTE: the '[...]_win_post_install.py' script is installed even on non-Windows
# platforms due to a bug in pip installation process
# See spyder-ide/spyder#1158.
SCRIPTS = ['%s_win_post_install.py' % NAME]
SCRIPTS.append('spyder')
if os.name == 'nt':
SCRIPTS += ['spyder.bat']
# =============================================================================
# Files added to the package
# =============================================================================
EXTLIST = ['.pot', '.po', '.mo', '.svg', '.png', '.css', '.html', '.js',
'.ini', '.txt', '.qss', '.ttf', '.json', '.rst', '.bloom',
'.ico', '.gif', '.mp3', '.ogg', '.sfd', '.bat', '.sh'] | setup.py | spyder | false | true | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 118 | 152 |
# =============================================================================
# Use Readme for long description
# =============================================================================
with io.open('README.md', encoding='utf-8') as f:
LONG_DESCRIPTION = f.read() | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 155 | 159 |
#==============================================================================
# Setup arguments
#==============================================================================
setup_args = dict(
name=NAME,
version=__version__,
description='The Scientific Python Development Environment',
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
download_url=__website_url__ + "#fh5co-download",
author="The Spyder Project Contributors",
author_email="spyder.python@gmail.com",
url=__website_url__,
license='MIT',
keywords='PyQt5 editor console widgets IDE science data analysis IPython',
platforms=["Windows", "Linux", "Mac OS-X"],
packages=get_packages(),
package_data={LIBNAME: get_package_data(LIBNAME, EXTLIST)},
scripts=[osp.join('scripts', fname) for fname in SCRIPTS],
data_files=get_data_files(),
python_requires='>=3.8',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Development Status :: 5 - Production/Stable', | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 162 | 194 |
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Widget Sets',
],
cmdclass=CMDCLASS,
) | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 192 | 202 |
install_requires = [
'applaunchservices>=0.3.0;platform_system=="Darwin"',
'atomicwrites>=1.2.0',
'chardet>=2.0.0',
'cloudpickle>=0.5.0',
'cookiecutter>=1.6.0',
'diff-match-patch>=20181111',
'intervaltree>=3.0.2',
'ipython>=8.12.2,<8.13.0; python_version=="3.8"',
'ipython>=8.13.0,<9.0.0,!=8.17.1; python_version>"3.8"',
'jedi>=0.17.2,<0.20.0',
'jellyfish>=0.7',
'jsonschema>=3.2.0',
'keyring>=17.0.0',
'nbconvert>=4.0',
'numpydoc>=0.6.0',
# Required to get SSH connections to remote kernels
'paramiko>=2.4.0;platform_system=="Windows"',
'parso>=0.7.0,<0.9.0',
'pexpect>=4.4.0',
'pickleshare>=0.4',
'psutil>=5.3',
'pygments>=2.0',
'pylint>=2.5.0,<3.1',
'pylint-venv>=3.0.2',
'pyls-spyder>=0.4.0',
'pyqt5>=5.15,<5.16',
'pyqtwebengine>=5.15,<5.16',
'python-lsp-black>=1.2.0,<3.0.0',
'python-lsp-server[all]>=1.9.0,<1.10.0',
'pyuca>=1.2',
'pyxdg>=0.26;platform_system=="Linux"',
'pyzmq>=22.1.0',
'qdarkstyle>=3.2.0,<3.3.0',
'qstylizer>=0.2.2',
'qtawesome>=1.2.1',
'qtconsole>=5.5.0,<5.6.0',
'qtpy>=2.4.0',
'rtree>=0.9.7',
'setuptools>=49.6.0',
'sphinx>=0.6.6',
'spyder-kernels>=3.0.0b2,<3.0.0b3',
'superqt>=0.6.1,<1.0.0',
'textdistance>=4.2.0',
'three-merge>=0.1.1',
'watchdog>=0.10.3'
] | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 205 | 251 |
# Loosen constraints to ensure dev versions still work
if 'dev' in __version__:
reqs_to_loosen = {'python-lsp-server[all]', 'qtconsole', 'spyder-kernels'}
install_requires = [req for req in install_requires
if req.split(">")[0] not in reqs_to_loosen]
install_requires.append('python-lsp-server[all]>=1.9.0,<1.11.0')
install_requires.append('qtconsole>=5.5.0,<5.7.0')
install_requires.append('spyder-kernels>=3.0.0b2,<3.1.0')
extras_require = {
'test:platform_system == "Windows"': ['pywin32'],
'test': [
'coverage',
'cython',
'flaky',
'matplotlib',
'pandas',
'pillow',
'pytest<7.0',
'pytest-cov',
'pytest-lazy-fixture',
'pytest-mock',
'pytest-order',
'pytest-qt',
'pytest-timeout',
'pyyaml',
'scipy',
'sympy',
],
} | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 253 | 282 |
spyder_plugins_entry_points = [
'appearance = spyder.plugins.appearance.plugin:Appearance',
'application = spyder.plugins.application.plugin:Application',
'completions = spyder.plugins.completion.plugin:CompletionPlugin',
'debugger = spyder.plugins.debugger.plugin:Debugger',
'editor = spyder.plugins.editor.plugin:Editor',
'explorer = spyder.plugins.explorer.plugin:Explorer',
'external_terminal = spyder.plugins.externalterminal.plugin:ExternalTerminal',
'find_in_files = spyder.plugins.findinfiles.plugin:FindInFiles',
'help = spyder.plugins.help.plugin:Help',
'historylog = spyder.plugins.history.plugin:HistoryLog',
'internal_console = spyder.plugins.console.plugin:Console',
'ipython_console = spyder.plugins.ipythonconsole.plugin:IPythonConsole',
'layout = spyder.plugins.layout.plugin:Layout',
'main_interpreter = spyder.plugins.maininterpreter.plugin:MainInterpreter',
'mainmenu = spyder.plugins.mainmenu.plugin:MainMenu',
'onlinehelp = spyder.plugins.onlinehelp.plugin:OnlineHelp',
'outline_explorer = spyder.plugins.outlineexplorer.plugin:OutlineExplorer',
'plots = spyder.plugins.plots.plugin:Plots',
'preferences = spyder.plugins.preferences.plugin:Preferences',
'profiler = spyder.plugins.profiler.plugin:Profiler',
'project_explorer = spyder.plugins.projects.plugin:Projects',
'pylint = spyder.plugins.pylint.plugin:Pylint', | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 285 | 307 |
'profiler = spyder.plugins.profiler.plugin:Profiler',
'project_explorer = spyder.plugins.projects.plugin:Projects',
'pylint = spyder.plugins.pylint.plugin:Pylint',
'pythonpath_manager = spyder.plugins.pythonpath.plugin:PythonpathManager',
'run = spyder.plugins.run.plugin:Run',
'shortcuts = spyder.plugins.shortcuts.plugin:Shortcuts',
'statusbar = spyder.plugins.statusbar.plugin:StatusBar',
'switcher = spyder.plugins.switcher.plugin:Switcher',
'toolbar = spyder.plugins.toolbar.plugin:Toolbar',
'tours = spyder.plugins.tours.plugin:Tours',
'variable_explorer = spyder.plugins.variableexplorer.plugin:VariableExplorer',
'workingdir = spyder.plugins.workingdirectory.plugin:WorkingDirectory',
] | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 305 | 317 |
spyder_completions_entry_points = [
('fallback = spyder.plugins.completion.providers.fallback.provider:'
'FallbackProvider'),
('snippets = spyder.plugins.completion.providers.snippets.provider:'
'SnippetsProvider'),
('lsp = spyder.plugins.completion.providers.languageserver.provider:'
'LanguageServerProvider'),
]
setup_args['install_requires'] = install_requires
setup_args['extras_require'] = extras_require
setup_args['entry_points'] = {
'gui_scripts': [
'spyder = spyder.app.start:main'
],
'spyder.plugins': spyder_plugins_entry_points,
'spyder.completions': spyder_completions_entry_points
}
setup_args.pop('scripts', None)
# =============================================================================
# Main setup
# =============================================================================
setup(**setup_args) | setup.py | spyder | false | false | [
"from __future__ import print_function",
"from distutils.command.install_data import install_data",
"import io",
"import os",
"import os.path as osp",
"import subprocess",
"import sys",
"from setuptools import setup, find_packages",
"from setuptools.command.install import install",
"from spyder import __version__, __website_url__ #analysis:ignore"
] | 319 | 344 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Configuration file for Pytest
NOTE: DO NOT add fixtures here. It could generate problems with
QtAwesome being called before a QApplication is created.
"""
import os
import os.path as osp
import re
import sys
# ---- To activate/deactivate certain things for pytest's only
# NOTE: Please leave this before any other import here!!
os.environ['SPYDER_PYTEST'] = 'True'
# ---- Pytest adjustments
import pytest
def pytest_addoption(parser):
"""Add option to run slow tests."""
parser.addoption("--run-slow", action="store_true",
default=False, help="Run slow tests")
def get_passed_tests():
"""
Get the list of passed tests by inspecting the log generated by pytest.
This is useful on CIs to restart the test suite from the point where a
segfault was thrown by it.
"""
# This assumes the pytest log is placed next to this file. That's where
# we put it on CIs.
if osp.isfile('pytest_log.txt'):
with open('pytest_log.txt') as f:
logfile = f.readlines()
# Detect all tests that passed before.
test_re = re.compile(r'(spyder.*) [^ ]*(SKIPPED|PASSED|XFAIL)')
tests = set()
for line in logfile:
match = test_re.match(line)
if match:
tests.add(match.group(1))
return tests
else:
return [] | conftest.py | spyder | false | true | [
"import os",
"import os.path as osp",
"import re",
"import sys",
"import pytest",
"from spyder.config.manager import CONF",
"from spyder.plugins.completion.api import COMPLETION_ENTRYPOINT",
"from spyder.plugins.completion.plugin import CompletionPlugin",
"from pkg_resources import iter_entry_points"
] | 1 | 56 |
def pytest_collection_modifyitems(config, items):
"""
Decide what tests to run (slow or fast) according to the --run-slow
option.
"""
passed_tests = get_passed_tests()
slow_option = config.getoption("--run-slow")
skip_slow = pytest.mark.skip(reason="Need --run-slow option to run")
skip_fast = pytest.mark.skip(reason="Don't need --run-slow option to run")
skip_passed = pytest.mark.skip(reason="Test passed in previous runs")
# Break test suite in CIs according to the following criteria:
# * Mark all main window tests, and a percentage of the IPython console
# ones, as slow.
# * All other tests will be considered as fast.
# This provides a more balanced partitioning of our test suite (in terms of
# necessary time to run it) between the slow and fast slots we have on CIs.
slow_items = []
if os.environ.get('CI'):
slow_items = [
item for item in items if 'test_mainwindow' in item.nodeid
]
ipyconsole_items = [
item for item in items if 'test_ipythonconsole' in item.nodeid
]
if os.name == 'nt':
percentage = 0.5
elif sys.platform == 'darwin':
percentage = 0.5
else:
percentage = 0.4
for i, item in enumerate(ipyconsole_items):
if i < len(ipyconsole_items) * percentage:
slow_items.append(item) | conftest.py | spyder | false | true | [
"import os",
"import os.path as osp",
"import re",
"import sys",
"import pytest",
"from spyder.config.manager import CONF",
"from spyder.plugins.completion.api import COMPLETION_ENTRYPOINT",
"from spyder.plugins.completion.plugin import CompletionPlugin",
"from pkg_resources import iter_entry_points"
] | 59 | 95 |
for i, item in enumerate(ipyconsole_items):
if i < len(ipyconsole_items) * percentage:
slow_items.append(item)
for item in items:
if slow_option:
if item not in slow_items:
item.add_marker(skip_fast)
else:
if item in slow_items:
item.add_marker(skip_slow)
if item.nodeid in passed_tests:
item.add_marker(skip_passed)
@pytest.fixture(autouse=True) | conftest.py | spyder | false | false | [
"import os",
"import os.path as osp",
"import re",
"import sys",
"import pytest",
"from spyder.config.manager import CONF",
"from spyder.plugins.completion.api import COMPLETION_ENTRYPOINT",
"from spyder.plugins.completion.plugin import CompletionPlugin",
"from pkg_resources import iter_entry_points"
] | 93 | 109 |
def reset_conf_before_test():
from spyder.config.manager import CONF
CONF.reset_to_defaults(notification=False)
from spyder.plugins.completion.api import COMPLETION_ENTRYPOINT
from spyder.plugins.completion.plugin import CompletionPlugin
# Restore completion clients default settings, since they
# don't have default values on the configuration.
from pkg_resources import iter_entry_points
provider_configurations = {}
for entry_point in iter_entry_points(COMPLETION_ENTRYPOINT):
Provider = entry_point.resolve()
provider_name = Provider.COMPLETION_PROVIDER_NAME
(provider_conf_version,
current_conf_values,
provider_defaults) = CompletionPlugin._merge_default_configurations(
Provider, provider_name, provider_configurations)
new_provider_config = {
'version': provider_conf_version,
'values': current_conf_values,
'defaults': provider_defaults
}
provider_configurations[provider_name] = new_provider_config
CONF.set('completions', 'provider_configuration', provider_configurations,
notification=False) | conftest.py | spyder | false | true | [
"import os",
"import os.path as osp",
"import re",
"import sys",
"import pytest",
"from spyder.config.manager import CONF",
"from spyder.plugins.completion.api import COMPLETION_ENTRYPOINT",
"from spyder.plugins.completion.plugin import CompletionPlugin",
"from pkg_resources import iter_entry_points"
] | 110 | 139 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""
Bootstrap Spyder.
Execute Spyder from source checkout.
"""
# Standard library imports
import argparse
import os
import shutil
import subprocess
import sys
import time
from logging import Formatter, StreamHandler, getLogger
from pathlib import Path
# Local imports
from install_dev_repos import DEVPATH, REPOS, install_repo
# =============================================================================
# ---- Setup logger
# =============================================================================
fmt = Formatter('%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s')
h = StreamHandler()
h.setFormatter(fmt)
logger = getLogger('Bootstrap')
logger.addHandler(h)
logger.setLevel('INFO')
time_start = time.time() | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 1 | 41 |
# =============================================================================
# ---- Parse command line
# =============================================================================
parser = argparse.ArgumentParser(
usage="python bootstrap.py [options] [-- spyder_options]",
epilog="""\
Arguments for Spyder's main script are specified after the --
symbol (example: `python bootstrap.py -- --hide-console`).
Type `python bootstrap.py -- --help` to read about Spyder
options.""")
parser.add_argument('--gui', default=None,
help="GUI toolkit: pyqt5 (for PyQt5) or pyside2 "
"(for PySide2)")
parser.add_argument('--hide-console', action='store_true', default=False,
help="Hide parent console window (Windows only)")
parser.add_argument('--safe-mode', dest="safe_mode",
action='store_true', default=False,
help="Start Spyder with a clean configuration directory")
parser.add_argument('--debug', action='store_true',
default=False, help="Run Spyder in debug mode")
parser.add_argument('--filter-log', default='',
help="Comma-separated module name hierarchies whose log "
"messages should be shown. e.g., "
"spyder.plugins.completion,spyder.plugins.editor")
parser.add_argument('--no-install', action='store_true', default=False,
help="Do not install Spyder or its subrepos") | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 44 | 69 |
parser.add_argument('--no-install', action='store_true', default=False,
help="Do not install Spyder or its subrepos")
parser.add_argument('spyder_options', nargs='*') | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 68 | 70 |
args = parser.parse_args()
assert args.gui in (None, 'pyqt5', 'pyside2'), \
"Invalid GUI toolkit option '%s'" % args.gui
# =============================================================================
# ---- Install sub repos
# =============================================================================
installed_dev_repo = False
if not args.no_install:
prev_branch = None
boot_branch_file = DEVPATH / ".boot_branch.txt"
if boot_branch_file.exists():
prev_branch = boot_branch_file.read_text()
result = subprocess.run(
["git", "-C", DEVPATH, "merge-base", "--fork-point", "master"],
capture_output=True
)
branch = "master" if result.stdout else "not master"
boot_branch_file.write_text(branch)
logger.info("Previous root branch: %s; current root branch: %s",
prev_branch, branch)
if branch != prev_branch:
logger.info("Detected root branch change to/from master. "
"Will reinstall Spyder in editable mode.")
REPOS[DEVPATH.name]["editable"] = False
for name in REPOS.keys():
if not REPOS[name]['editable']:
install_repo(name)
installed_dev_repo = True
else:
logger.info("%s installed in editable mode", name) | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 72 | 108 |
if installed_dev_repo:
logger.info("Restarting bootstrap to pick up installed subrepos")
if '--' in sys.argv:
sys.argv.insert(sys.argv.index('--'), '--no-install')
else:
sys.argv.append('--no-install')
result = subprocess.run([sys.executable, *sys.argv])
sys.exit(result.returncode)
# Local imports
# Must follow install_repo in case Spyder was not originally installed.
from spyder import get_versions
logger.info("Executing Spyder from source checkout")
# Prepare arguments for Spyder's main script
original_sys_argv = sys.argv.copy()
sys.argv = [sys.argv[0]] + args.spyder_options
# =============================================================================
# ---- Update os.environ
# =============================================================================
# Store variable to be used in self.restart (restart Spyder instance)
os.environ['SPYDER_BOOTSTRAP_ARGS'] = str(original_sys_argv[1:])
# Start Spyder with a clean configuration directory for testing purposes
if args.safe_mode:
os.environ['SPYDER_SAFE_MODE'] = 'True'
# To activate/deactivate certain things for development
os.environ['SPYDER_DEV'] = 'True' | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 110 | 141 |
# To activate/deactivate certain things for development
os.environ['SPYDER_DEV'] = 'True'
if args.debug:
# safety check - Spyder config should not be imported at this point
if "spyder.config.base" in sys.modules:
sys.exit("ERROR: Can't enable debug mode - Spyder is already imported")
logger.info("Switching debug mode on")
os.environ["SPYDER_DEBUG"] = "3"
if len(args.filter_log) > 0:
logger.info("Displaying log messages only from the "
"following modules: %s", args.filter_log)
os.environ["SPYDER_FILTER_LOG"] = args.filter_log
# this way of interaction suxx, because there is no feedback
# if operation is successful
# Selecting the GUI toolkit: PyQt5 if installed
if args.gui is None:
try:
import PyQt5 # analysis:ignore
logger.info("PyQt5 is detected, selecting")
os.environ['QT_API'] = 'pyqt5'
except ImportError:
sys.exit("ERROR: No PyQt5 detected!")
else:
logger.info("Skipping GUI toolkit detection")
os.environ['QT_API'] = args.gui | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 140 | 166 |
# =============================================================================
# ---- Check versions
# =============================================================================
# Checking versions (among other things, this has the effect of setting the
# QT_API environment variable if this has not yet been done just above)
versions = get_versions(reporev=True)
logger.info("Imported Spyder %s - Revision %s, Branch: %s; "
"[Python %s %dbits, Qt %s, %s %s on %s]",
versions['spyder'], versions['revision'], versions['branch'],
versions['python'], versions['bitness'], versions['qt'],
versions['qt_api'], versions['qt_api_ver'], versions['system'])
# Check that we have the right qtpy version
from spyder.utils import programs
if not programs.is_module_installed('qtpy', '>=1.1.0'):
sys.exit("ERROR: Your qtpy version is outdated. Please install qtpy "
"1.1.0 or higher to be able to work with Spyder!")
# =============================================================================
# ---- Execute Spyder
# =============================================================================
if args.hide_console and os.name == 'nt':
logger.info("Hiding parent console (Windows only)")
sys.argv.append("--hide-console") # Windows only: show parent console | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 169 | 193 |
# Reset temporary config directory if starting in --safe-mode
if args.safe_mode or os.environ.get('SPYDER_SAFE_MODE'):
from spyder.config.base import get_conf_path # analysis:ignore
conf_dir = Path(get_conf_path())
if conf_dir.is_dir():
shutil.rmtree(conf_dir)
logger.info("Running Spyder")
from spyder.app import start # analysis:ignore
time_lapse = time.time() - time_start
logger.info("Bootstrap completed in %s%s",
time.strftime("%H:%M:%S.", time.gmtime(time_lapse)),
# gmtime() converts float into tuple, but loses milliseconds
("%.4f" % time_lapse).split('.')[1])
start.main() | bootstrap.py | spyder | false | false | [
"import argparse",
"import os",
"import shutil",
"import subprocess",
"import sys",
"import time",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from install_dev_repos import DEVPATH, REPOS, install_repo",
"from spyder import get_versions",
"import PyQt5 # analysis:ignore",
"from spyder.utils import programs",
"from spyder.config.base import get_conf_path # analysis:ignore",
"from spyder.app import start # analysis:ignore"
] | 195 | 211 |
# postinstall script for Spyder
"""Create Spyder start menu and desktop entries"""
from __future__ import print_function
import os
import sys
import os.path as osp
import struct
import winreg
EWS = "Edit with Spyder"
KEY_C = r"Software\Classes\%s"
KEY_C0 = KEY_C % r"Python.%sFile\shell\%s"
KEY_C1 = KEY_C0 + r"\command"
# ability to run spyder-win-post-install outside of bdist_wininst installer
# copied from pywin32-win-post-install.py
# http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/file/default/pywin32_postinstall.py
ver_string = "%d.%d" % (sys.version_info[0], sys.version_info[1])
root_key_name = "Software\\Python\\PythonCore\\" + ver_string
try:
# When this script is run from inside the bdist_wininst installer,
# file_created() and directory_created() are additional builtin
# functions which write lines to Python23\pywin32-install.log. This is
# a list of actions for the uninstaller, the format is inspired by what
# the Wise installer also creates.
# https://docs.python.org/2/distutils/builtdist.html#the-postinstallation-script
file_created # analysis:ignore
is_bdist_wininst = True
except NameError:
is_bdist_wininst = False # we know what it is not - but not what it is :) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 1 | 35 |
# file_created() and directory_created() functions do nothing if post
# install script isn't run from bdist_wininst installer, instead if
# shortcuts and start menu directory exist, they are removed when the
# post install script is called with the -remote option
def file_created(file):
pass
def directory_created(directory):
pass
def get_root_hkey():
try:
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
root_key_name, 0, winreg.KEY_CREATE_SUB_KEY)
return winreg.HKEY_LOCAL_MACHINE
except OSError:
# Either not exist, or no permissions to create subkey means
# must be HKCU
return winreg.HKEY_CURRENT_USER
try:
create_shortcut # analysis:ignore
except NameError:
# Create a function with the same signature as create_shortcut
# provided by bdist_wininst
def create_shortcut(path, description, filename,
arguments="", workdir="", iconpath="", iconindex=0):
try:
import pythoncom
except ImportError:
print("pywin32 is required to run this script manually",
file=sys.stderr)
sys.exit(1)
from win32com.shell import shell, shellcon # analysis:ignore | spyder_win_post_install.py | spyder.scripts | false | true | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 37 | 67 |
ilink = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IShellLink)
ilink.SetPath(path)
ilink.SetDescription(description)
if arguments:
ilink.SetArguments(arguments)
if workdir:
ilink.SetWorkingDirectory(workdir)
if iconpath or iconindex:
ilink.SetIconLocation(iconpath, iconindex)
# now save it.
ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile)
ipf.Save(filename, 0)
# Support the same list of "path names" as bdist_wininst.
def get_special_folder_path(path_name):
try:
import pythoncom
except ImportError:
print("pywin32 is required to run this script manually",
file=sys.stderr)
sys.exit(1)
from win32com.shell import shell, shellcon | spyder_win_post_install.py | spyder.scripts | false | true | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 69 | 92 |
path_names = ['CSIDL_COMMON_STARTMENU', 'CSIDL_STARTMENU',
'CSIDL_COMMON_APPDATA', 'CSIDL_LOCAL_APPDATA',
'CSIDL_APPDATA', 'CSIDL_COMMON_DESKTOPDIRECTORY',
'CSIDL_DESKTOPDIRECTORY', 'CSIDL_COMMON_STARTUP',
'CSIDL_STARTUP', 'CSIDL_COMMON_PROGRAMS',
'CSIDL_PROGRAMS', 'CSIDL_PROGRAM_FILES_COMMON',
'CSIDL_PROGRAM_FILES', 'CSIDL_FONTS']
for maybe in path_names:
if maybe == path_name:
csidl = getattr(shellcon, maybe)
return shell.SHGetSpecialFolderPath(0, csidl, False)
raise ValueError("%s is an unknown path ID" % (path_name,)) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 94 | 105 |
def install():
"""Function executed when running the script with the -install switch"""
# Create Spyder start menu folder
# Don't use CSIDL_COMMON_PROGRAMS because it requres admin rights
# This is consistent with use of CSIDL_DESKTOPDIRECTORY below
# CSIDL_COMMON_PROGRAMS =
# C:\ProgramData\Microsoft\Windows\Start Menu\Programs
# CSIDL_PROGRAMS =
# C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
start_menu = osp.join(get_special_folder_path('CSIDL_PROGRAMS'),
'Spyder (Py%i.%i %i bit)' % (sys.version_info[0],
sys.version_info[1],
struct.calcsize('P')*8))
if not osp.isdir(start_menu):
os.mkdir(start_menu)
directory_created(start_menu) | spyder_win_post_install.py | spyder.scripts | false | true | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 108 | 123 |
# Create Spyder start menu entries
python = osp.abspath(osp.join(sys.prefix, 'python.exe'))
pythonw = osp.abspath(osp.join(sys.prefix, 'pythonw.exe'))
script = osp.abspath(osp.join(sys.prefix, 'scripts', 'spyder'))
if not osp.exists(script): # if not installed to the site scripts dir
script = osp.abspath(osp.join(osp.dirname(osp.abspath(__file__)), 'spyder'))
workdir = "%HOMEDRIVE%%HOMEPATH%"
lib_dir = sysconfig.get_path("platlib")
ico_dir = osp.join(lib_dir, 'spyder', 'windows')
# if user is running -install manually then icons are in Scripts/
if not osp.isdir(ico_dir):
ico_dir = osp.dirname(osp.abspath(__file__))
desc = 'The Scientific Python Development Environment'
fname = osp.join(start_menu, 'Spyder (full).lnk')
create_shortcut(python, desc, fname, '"%s"' % script, workdir,
osp.join(ico_dir, 'spyder.ico'))
file_created(fname)
fname = osp.join(start_menu, 'Spyder-Reset all settings.lnk')
create_shortcut(python, 'Reset Spyder settings to defaults',
fname, '"%s" --reset' % script, workdir)
file_created(fname) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 125 | 147 |
current = True # only affects current user
root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE
winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("", EWS)),
"", 0, winreg.REG_SZ,
'"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix))
winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("NoCon", EWS)),
"", 0, winreg.REG_SZ,
'"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix))
# Create desktop shortcut file
desktop_folder = get_special_folder_path("CSIDL_DESKTOPDIRECTORY")
fname = osp.join(desktop_folder, 'Spyder.lnk')
desc = 'The Scientific Python Development Environment'
create_shortcut(pythonw, desc, fname, '"%s"' % script, workdir,
osp.join(ico_dir, 'spyder.ico'))
file_created(fname) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 149 | 164 |
def remove():
"""Function executed when running the script with the -remove switch"""
current = True # only affects current user
root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE
for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS),
KEY_C0 % ("", EWS), KEY_C0 % ("NoCon", EWS)):
try:
winreg.DeleteKey(root, key)
except WindowsError:
pass
else:
if not is_bdist_wininst:
print("Successfully removed Spyder shortcuts from Windows "\
"Explorer context menu.", file=sys.stdout)
if not is_bdist_wininst:
# clean up desktop
desktop_folder = get_special_folder_path("CSIDL_DESKTOPDIRECTORY")
fname = osp.join(desktop_folder, 'Spyder.lnk')
if osp.isfile(fname):
try:
os.remove(fname)
except OSError:
print("Failed to remove %s; you may be able to remove it "\
"manually." % fname, file=sys.stderr)
else:
print("Successfully removed Spyder shortcuts from your desktop.",
file=sys.stdout)
# clean up startmenu
start_menu = osp.join(get_special_folder_path('CSIDL_PROGRAMS'),
'Spyder (Py%i.%i %i bit)' % (sys.version_info[0],
sys.version_info[1], | spyder_win_post_install.py | spyder.scripts | false | true | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 167 | 197 |
'Spyder (Py%i.%i %i bit)' % (sys.version_info[0],
sys.version_info[1],
struct.calcsize('P')*8))
if osp.isdir(start_menu):
for fname in os.listdir(start_menu):
try:
os.remove(osp.join(start_menu,fname))
except OSError:
print("Failed to remove %s; you may be able to remove it "\
"manually." % fname, file=sys.stderr)
else:
print("Successfully removed Spyder shortcuts from your "\
" start menu.", file=sys.stdout)
try:
os.rmdir(start_menu)
except OSError:
print("Failed to remove %s; you may be able to remove it "\
"manually." % fname, file=sys.stderr)
else:
print("Successfully removed Spyder shortcut folder from your "\
" start menu.", file=sys.stdout) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 118 | 138 |
if __name__=='__main__':
if len(sys.argv) > 1:
if sys.argv[1] == '-install':
try:
install()
except OSError:
print("Failed to create Start Menu items.", file=sys.stderr)
elif sys.argv[1] == '-remove':
remove()
else:
print("Unknown command line option %s" % sys.argv[1],
file=sys.stderr)
else:
print("You need to pass either -install or -remove as options to "\
"this script", file=sys.stderr) | spyder_win_post_install.py | spyder.scripts | false | false | [
"from __future__ import print_function",
"import os",
"import sys",
"import os.path as osp",
"import struct",
"import winreg",
"import pythoncom",
"from win32com.shell import shell, shellcon # analysis:ignore",
"import pythoncom",
"from win32com.shell import shell, shellcon"
] | 219 | 233 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# Standard library imports
import os
import re
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
from configparser import ConfigParser
from datetime import timedelta
from logging import Formatter, StreamHandler, getLogger
from pathlib import Path
from subprocess import check_call
from textwrap import dedent
from time import time
# Third-party imports
from git import Repo, rmtree
from ruamel.yaml import YAML
from setuptools_scm import get_version
fmt = Formatter('%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s')
h = StreamHandler()
h.setFormatter(fmt)
logger = getLogger('BuildCondaPkgs')
logger.addHandler(h)
logger.setLevel('INFO')
HERE = Path(__file__).parent
BUILD = HERE / "build"
RESOURCES = HERE / "resources"
EXTDEPS = HERE.parent / "external-deps"
SPECS = BUILD / "specs.yaml"
REQUIREMENTS = HERE.parent / "requirements"
REQ_MAIN = REQUIREMENTS / 'main.yml'
REQ_WINDOWS = REQUIREMENTS / 'windows.yml'
REQ_MAC = REQUIREMENTS / 'macos.yml'
REQ_LINUX = REQUIREMENTS / 'linux.yml'
BUILD.mkdir(exist_ok=True)
SPYPATCHFILE = BUILD / "installers-conda.patch" | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 1 | 44 |
class BuildCondaPkg:
"""Base class for building a conda package for conda-based installer"""
name = None
norm = True
source = None
feedstock = None
shallow_ver = None
def __init__(self, data={}, debug=False, shallow=False):
self.logger = getLogger(self.__class__.__name__)
if not self.logger.handlers:
self.logger.addHandler(h)
self.logger.setLevel('INFO')
self.debug = debug
self._bld_src = BUILD / self.name
self._fdstk_path = BUILD / self.feedstock.split("/")[-1]
self._get_source(shallow=shallow)
self._get_version()
self._patch_source()
self.data = {'version': self.version}
self.data.update(data)
self._recipe_patched = False
def _get_source(self, shallow=False):
"""Clone source and feedstock to distribution directory for building"""
self._build_cleanup()
if self.source == HERE.parent:
self._bld_src = self.source
self.repo = Repo(self.source)
else:
# Determine source and commit
if self.source is not None:
remote = self.source
commit = 'HEAD'
else:
cfg = ConfigParser()
cfg.read(EXTDEPS / self.name / '.gitrepo')
remote = cfg['subrepo']['remote']
commit = cfg['subrepo']['commit'] | build_conda_pkgs.py | spyder.installers-conda | true | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 47 | 92 |
# Clone from source
kwargs = dict(to_path=self._bld_src)
if shallow:
kwargs.update(shallow_exclude=self.shallow_ver)
self.logger.info(
f"Cloning source shallow from tag {self.shallow_ver}...")
else:
self.logger.info("Cloning source...")
self.repo = Repo.clone_from(remote, **kwargs)
self.repo.git.checkout(commit)
# Clone feedstock
self.logger.info("Cloning feedstock...")
Repo.clone_from(self.feedstock, to_path=self._fdstk_path)
def _build_cleanup(self):
"""Remove cloned source and feedstock repositories"""
for src in [self._bld_src, self._fdstk_path]:
if src.exists() and src != HERE.parent:
logger.info(f"Removing {src}...")
rmtree(src)
def _get_version(self):
"""Get source version using setuptools_scm"""
v = get_version(self._bld_src, normalize=self.norm)
self.version = v.lstrip('v').split('+')[0]
def _patch_source(self):
pass
def _patch_meta(self, meta):
return meta
def _patch_build_script(self):
pass
def patch_recipe(self):
"""
Patch conda build recipe
1. Patch meta.yaml
2. Patch build script
"""
if self._recipe_patched:
return
self.logger.info("Patching 'meta.yaml'...") | build_conda_pkgs.py | spyder.installers-conda | false | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 94 | 140 |
1. Patch meta.yaml
2. Patch build script
"""
if self._recipe_patched:
return
self.logger.info("Patching 'meta.yaml'...")
file = self._fdstk_path / "recipe" / "meta.yaml"
meta = file.read_text()
# Replace jinja variable values
for k, v in self.data.items():
meta = re.sub(f".*set {k} =.*", f'{{% set {k} = "{v}" %}}', meta)
# Replace source, but keep patches
meta = re.sub(r'^(source:\n)( (url|sha256):.*\n)*',
rf'\g<1> path: {self._bld_src.as_posix()}\n',
meta, flags=re.MULTILINE)
meta = self._patch_meta(meta)
file.rename(file.parent / ("_" + file.name)) # keep copy of original
file.write_text(meta)
self.logger.info(f"Patched 'meta.yaml' contents:\n{file.read_text()}")
self._patch_build_script()
self._recipe_patched = True
def build(self):
"""
Build the conda package.
1. Patch the recipe
2. Build the package
3. Remove cloned repositories
"""
t0 = time()
try:
self.patch_recipe() | build_conda_pkgs.py | spyder.installers-conda | false | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 134 | 175 |
1. Patch the recipe
2. Build the package
3. Remove cloned repositories
"""
t0 = time()
try:
self.patch_recipe()
self.logger.info("Building conda package "
f"{self.name}={self.version}...")
check_call([
"mamba", "mambabuild",
"--no-test", "--skip-existing", "--build-id-pat={n}",
str(self._fdstk_path / "recipe")
])
finally:
self._recipe_patched = False
if self.debug:
self.logger.info("Keeping cloned source and feedstock")
else:
self._build_cleanup()
elapse = timedelta(seconds=int(time() - t0))
self.logger.info(f"Build time = {elapse}") | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 169 | 192 |
class SpyderCondaPkg(BuildCondaPkg):
name = "spyder"
norm = False
source = os.environ.get('SPYDER_SOURCE', HERE.parent)
feedstock = "https://github.com/conda-forge/spyder-feedstock"
shallow_ver = "v5.3.2"
def _patch_source(self):
self.logger.info("Creating Spyder menu file...")
_menufile = RESOURCES / "spyder-menu.json"
self.menufile = BUILD / "spyder-menu.json"
commit, branch = self.repo.head.commit.name_rev.split()
text = _menufile.read_text()
text = text.replace("__PKG_VERSION__", self.version)
text = text.replace("__SPY_BRANCH__", branch)
text = text.replace("__SPY_COMMIT__", commit[:8])
self.menufile.write_text(text)
def _patch_meta(self, meta):
# Remove osx_is_app
meta = re.sub(r'^(build:\n([ ]{2,}.*\n)*) osx_is_app:.*\n',
r'\g<1>', meta, flags=re.MULTILINE)
# Remove app node
meta = re.sub(r'^app:\n( .*\n)+', '', meta, flags=re.MULTILINE) | build_conda_pkgs.py | spyder.installers-conda | false | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 195 | 219 |
# Remove app node
meta = re.sub(r'^app:\n( .*\n)+', '', meta, flags=re.MULTILINE)
# Get current Spyder requirements
yaml = YAML()
current_requirements = ['python']
current_requirements += yaml.load(
REQ_MAIN.read_text())['dependencies']
if os.name == 'nt':
win_requirements = yaml.load(
REQ_WINDOWS.read_text())['dependencies']
current_requirements += win_requirements
current_requirements.append('ptyprocess >=0.5')
elif sys.platform == 'darwin':
mac_requirements = yaml.load(
REQ_MAC.read_text())['dependencies']
if 'python.app' in mac_requirements:
mac_requirements.remove('python.app')
current_requirements += mac_requirements
else:
linux_requirements = yaml.load(
REQ_LINUX.read_text())['dependencies']
current_requirements += linux_requirements
# Replace run requirements
cr_string = '\n - '.join(current_requirements)
meta = re.sub(r'^(requirements:\n(.*\n)+ run:\n)( .*\n)+',
rf'\g<1> - {cr_string}\n', meta, flags=re.MULTILINE)
return meta
def _patch_build_script(self):
self.logger.info("Patching build script...")
rel_menufile = self.menufile.relative_to(HERE.parent) | build_conda_pkgs.py | spyder.installers-conda | false | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 218 | 252 |
return meta
def _patch_build_script(self):
self.logger.info("Patching build script...")
rel_menufile = self.menufile.relative_to(HERE.parent)
if os.name == 'posix':
logomark = "branding/logo/logomark/spyder-logomark-background.png"
file = self._fdstk_path / "recipe" / "build.sh"
text = file.read_text()
text += dedent(
f"""
# Create the Menu directory
mkdir -p "${{PREFIX}}/Menu"
# Copy menu.json template
cp "${{SRC_DIR}}/{rel_menufile}" "${{PREFIX}}/Menu/spyder-menu.json"
# Copy application icons
if [[ $OSTYPE == "darwin"* ]]; then
cp "${{SRC_DIR}}/img_src/spyder.icns" "${{PREFIX}}/Menu/spyder.icns"
else
cp "${{SRC_DIR}}/{logomark}" "${{PREFIX}}/Menu/spyder.png"
fi
"""
)
if os.name == 'nt':
file = self._fdstk_path / "recipe" / "bld.bat"
text = file.read_text()
text = text.replace(
r"copy %RECIPE_DIR%\menu-windows.json %MENU_DIR%\spyder_shortcut.json",
fr"copy %SRC_DIR%\{rel_menufile} %MENU_DIR%\spyder-menu.json"
)
file.rename(file.parent / ("_" + file.name)) # keep copy of original
file.write_text(text) | build_conda_pkgs.py | spyder.installers-conda | false | true | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 125 | 161 |
self.logger.info(f"Patched build script contents:\n{file.read_text()}") | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | -1 | -1 |
class PylspCondaPkg(BuildCondaPkg):
name = "python-lsp-server"
source = os.environ.get('PYTHON_LSP_SERVER_SOURCE')
feedstock = "https://github.com/conda-forge/python-lsp-server-feedstock"
shallow_ver = "v1.4.1"
class QtconsoleCondaPkg(BuildCondaPkg):
name = "qtconsole"
source = os.environ.get('QTCONSOLE_SOURCE')
feedstock = "https://github.com/conda-forge/qtconsole-feedstock"
shallow_ver = "5.3.1" | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 288 | 299 |
class SpyderKernelsCondaPkg(BuildCondaPkg):
name = "spyder-kernels"
source = os.environ.get('SPYDER_KERNELS_SOURCE')
feedstock = "https://github.com/conda-forge/spyder-kernels-feedstock"
shallow_ver = "v2.3.1"
PKGS = {
SpyderCondaPkg.name: SpyderCondaPkg,
PylspCondaPkg.name: PylspCondaPkg,
QtconsoleCondaPkg.name: QtconsoleCondaPkg,
SpyderKernelsCondaPkg.name: SpyderKernelsCondaPkg
}
if __name__ == "__main__":
p = ArgumentParser(
description=dedent(
"""
Build conda packages to local channel.
This module builds conda packages for Spyder and external-deps for
inclusion in the conda-based installer. The following classes are
provided for each package:
SpyderCondaPkg
PylspCondaPkg
QdarkstyleCondaPkg
QtconsoleCondaPkg
SpyderKernelsCondaPkg
Spyder will be packaged from this repository (in its checked-out
state). qtconsole, spyder-kernels, and python-lsp-server will be
packaged from the remote and commit specified in their respective
.gitrepo files in external-deps. | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 302 | 334 |
Alternatively, any external-deps may be packaged from an arbitrary
git repository (in its checked out state) by setting the
appropriate environment variable from the following:
SPYDER_SOURCE
PYTHON_LSP_SERVER_SOURCE
QDARKSTYLE_SOURCE
QTCONSOLE_SOURCE
SPYDER_KERNELS_SOURCE
"""
),
usage="python build_conda_pkgs.py "
"[--build BUILD [BUILD] ...] [--debug] [--shallow]",
formatter_class=RawTextHelpFormatter
)
p.add_argument(
'--debug', action='store_true', default=False,
help="Do not remove cloned sources and feedstocks"
)
p.add_argument(
'--build', nargs="+", default=PKGS.keys(),
help=("Space-separated list of packages to build. "
f"Default is {list(PKGS.keys())}")
)
p.add_argument(
'--shallow', action='store_true', default=False,
help="Perform shallow clone for build")
args = p.parse_args()
logger.info(f"Building local conda packages {list(args.build)}...")
t0 = time()
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
if SPECS.exists():
specs = yaml.load(SPECS.read_text())
else:
specs = {k: "" for k in PKGS}
for k in args.build:
pkg = PKGS[k](debug=args.debug, shallow=args.shallow)
pkg.build()
specs[k] = "=" + pkg.version | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 336 | 378 |
for k in args.build:
pkg = PKGS[k](debug=args.debug, shallow=args.shallow)
pkg.build()
specs[k] = "=" + pkg.version
yaml.dump(specs, SPECS)
elapse = timedelta(seconds=int(time() - t0))
logger.info(f"Total build time = {elapse}") | build_conda_pkgs.py | spyder.installers-conda | false | false | [
"import os",
"import re",
"import sys",
"from argparse import ArgumentParser, RawTextHelpFormatter",
"from configparser import ConfigParser",
"from datetime import timedelta",
"from logging import Formatter, StreamHandler, getLogger",
"from pathlib import Path",
"from subprocess import check_call",
"from textwrap import dedent",
"from time import time",
"from git import Repo, rmtree",
"from ruamel.yaml import YAML",
"from setuptools_scm import get_version"
] | 375 | 383 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Create Spyder installers using `constructor`.
It creates a `construct.yaml` file with the needed settings
and then runs `constructor`.
Some environment variables we use:
CONSTRUCTOR_TARGET_PLATFORM:
conda-style platform (as in `platform` in `conda info -a` output)
CONSTRUCTOR_CONDA_EXE:
when the target platform is not the same as the host, constructor
needs a path to a conda-standalone (or micromamba) executable for
that platform. needs to be provided in this env var in that case!
CONSTRUCTOR_SIGNING_CERTIFICATE:
Path to PFX certificate to sign the EXE installer on Windows
"""
# Standard library imports
from argparse import ArgumentParser
from datetime import timedelta
from distutils.spawn import find_executable
from functools import partial
import json
from logging import getLogger
import os
from pathlib import Path
import platform
import re
from subprocess import check_call
import sys
from textwrap import dedent, indent
from time import time
import zipfile
# Third-party imports
from ruamel.yaml import YAML
# Local imports
from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version
DIST = HERE / "dist"
logger = getLogger('BuildInstallers')
logger.addHandler(h)
logger.setLevel('INFO') | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 1 | 52 |
# Local imports
from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version
DIST = HERE / "dist"
logger = getLogger('BuildInstallers')
logger.addHandler(h)
logger.setLevel('INFO')
APP = "Spyder"
SPYREPO = HERE.parent
WINDOWS = os.name == "nt"
MACOS = sys.platform == "darwin"
LINUX = sys.platform.startswith("linux")
TARGET_PLATFORM = os.environ.get("CONSTRUCTOR_TARGET_PLATFORM")
PY_VER = "{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info)
if TARGET_PLATFORM == "osx-arm64":
ARCH = "arm64"
else:
ARCH = (platform.machine() or "generic").lower().replace("amd64", "x86_64")
if WINDOWS:
OS = "Windows"
INSTALL_CHOICES = ["exe"]
elif LINUX:
OS = "Linux"
INSTALL_CHOICES = ["sh"]
elif MACOS:
OS = "macOS"
INSTALL_CHOICES = ["pkg", "sh"]
else:
raise RuntimeError(f"Unrecognized OS: {sys.platform}")
scientific_packages = {
"cython": "",
"matplotlib": "",
"numpy": "",
"openpyxl": "",
"pandas": "",
"scipy": "",
"sympy": "",
} | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 45 | 86 |
scientific_packages = {
"cython": "",
"matplotlib": "",
"numpy": "",
"openpyxl": "",
"pandas": "",
"scipy": "",
"sympy": "",
}
# ---- Parse arguments
p = ArgumentParser()
p.add_argument(
"--no-local", action="store_true",
help="Do not use local conda packages"
)
p.add_argument(
"--debug", action="store_true",
help="Do not delete build files"
)
p.add_argument(
"--arch", action="store_true",
help="Print machine architecture tag and exit.",
)
p.add_argument(
"--ext", action="store_true",
help="Print installer extension for this platform and exit.",
)
p.add_argument(
"--artifact-name", action="store_true",
help="Print computed artifact name and exit.",
)
p.add_argument(
"--extra-specs", nargs="+", default=[],
help="One or more extra conda specs to add to the installer",
)
p.add_argument(
"--licenses", action="store_true",
help="Post-process licenses AFTER having built the installer. "
"This must be run as a separate step.",
)
p.add_argument(
"--images", action="store_true",
help="Generate background images from the logo (test only)",
)
p.add_argument(
"--cert-id", default=None,
help="Apple Developer ID Application certificate common name."
)
p.add_argument(
"--install-type", choices=INSTALL_CHOICES, default=INSTALL_CHOICES[0],
help="Installer type."
)
args = p.parse_args() | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 78 | 131 |
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
indent4 = partial(indent, prefix=" ")
SPYVER = get_version(SPYREPO, normalize=False).lstrip('v').split("+")[0]
specs = {
"python": "=" + PY_VER,
"spyder": "=" + SPYVER,
}
specs.update(scientific_packages)
if SPECS.exists():
logger.info(f"Reading specs from {SPECS}...")
_specs = yaml.load(SPECS.read_text())
specs.update(_specs)
else:
logger.info(f"Did not read specs from {SPECS}")
for spec in args.extra_specs:
k, *v = re.split('([<>= ]+)', spec)
specs[k] = "".join(v).strip()
if k == "spyder":
SPYVER = v[-1]
OUTPUT_FILE = DIST / f"{APP}-{SPYVER}-{OS}-{ARCH}.{args.install_type}"
INSTALLER_DEFAULT_PATH_STEM = f"{APP.lower()}-{SPYVER.split('.')[0]}"
WELCOME_IMG_WIN = BUILD / "welcome_img_win.png"
HEADER_IMG_WIN = BUILD / "header_img_win.png"
WELCOME_IMG_MAC = BUILD / "welcome_img_mac.png" | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 133 | 163 |
def _generate_background_images(installer_type):
"""This requires Pillow."""
if installer_type == "sh":
# shell installers are text-based, no graphics
return
from PIL import Image
logo_path = SPYREPO / "img_src" / "spyder.png"
logo = Image.open(logo_path, "r")
if installer_type in ("exe", "all"):
sidebar = Image.new("RGBA", (164, 314), (0, 0, 0, 0))
sidebar.paste(logo.resize((101, 101)), (32, 180))
output = WELCOME_IMG_WIN
sidebar.save(output, format="png")
banner = Image.new("RGBA", (150, 57), (0, 0, 0, 0))
banner.paste(logo.resize((44, 44)), (8, 6))
output = HEADER_IMG_WIN
banner.save(output, format="png")
if installer_type in ("pkg", "all"):
_logo = Image.new("RGBA", logo.size, "WHITE")
_logo.paste(logo, mask=logo)
background = Image.new("RGBA", (1227, 600), (0, 0, 0, 0))
background.paste(_logo.resize((148, 148)), (95, 418))
output = WELCOME_IMG_MAC
background.save(output, format="png") | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 166 | 194 |
def _get_condarc():
# we need defaults for tensorflow and others on windows only
defaults = "- defaults" if WINDOWS else ""
prompt = "[spyder]({default_env}) "
contents = dedent(
f"""
channels: #!final
- conda-forge
{defaults}
repodata_fns: #!final
- repodata.json
auto_update_conda: false #!final
notify_outdated_conda: false #!final
channel_priority: strict #!final
env_prompt: '{prompt}' #! final
"""
)
# the undocumented #!final comment is explained here
# https://www.anaconda.com/blog/conda-configuration-engine-power-users
file = BUILD / "condarc"
file.write_text(contents)
return str(file) | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 197 | 219 |
def _definitions():
condarc = _get_condarc()
definitions = {
"name": APP,
"company": "Spyder-IDE",
"reverse_domain_identifier": "org.spyder-ide.Spyder",
"version": SPYVER,
"channels": [
"napari/label/bundle_tools_3",
"conda-forge/label/spyder_kernels_rc",
"conda-forge",
],
"conda_default_channels": ["conda-forge"],
"specs": [
f"python={PY_VER}",
"mamba",
],
"installer_filename": OUTPUT_FILE.name,
"installer_type": args.install_type,
"initialize_by_default": False,
"initialize_conda": False,
"register_python": False,
"extra_envs": {
"spyder-runtime": {
"specs": [k + v for k, v in specs.items()],
},
},
"extra_files": [
{str(RESOURCES / "bundle_readme.md"): "README.txt"},
{condarc: ".condarc"},
],
}
if not args.no_local:
definitions["channels"].insert(0, "local")
definitions["license_file"] = str(RESOURCES / "bundle_license.rtf")
if args.install_type == "sh":
definitions["license_file"] = str(SPYREPO / "LICENSE.txt") | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 222 | 260 |
definitions["license_file"] = str(RESOURCES / "bundle_license.rtf")
if args.install_type == "sh":
definitions["license_file"] = str(SPYREPO / "LICENSE.txt")
if LINUX:
definitions.update(
{
"default_prefix": os.path.join(
"$HOME", ".local", INSTALLER_DEFAULT_PATH_STEM
),
"post_install": str(RESOURCES / "post-install.sh"),
}
)
if MACOS:
welcome_text_tmpl = \
(RESOURCES / "osx_pkg_welcome.rtf.tmpl").read_text()
welcome_file = BUILD / "osx_pkg_welcome.rtf"
welcome_file.write_text(
welcome_text_tmpl.replace("__VERSION__", SPYVER))
definitions.update(
{
"post_install": str(RESOURCES / "post-install.sh"),
"conclusion_text": "",
"readme_text": "",
# For sh installer
"default_prefix": os.path.join(
"$HOME", "Library", INSTALLER_DEFAULT_PATH_STEM
),
# For pkg installer
"pkg_name": INSTALLER_DEFAULT_PATH_STEM,
"default_location_pkg": "Library",
"welcome_image": str(WELCOME_IMG_MAC),
"welcome_file": str(welcome_file),
}
) | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 258 | 294 |
if args.cert_id:
definitions["signing_identity_name"] = args.cert_id
definitions["notarization_identity_name"] = args.cert_id
if WINDOWS:
definitions["conda_default_channels"].append("defaults")
definitions.update(
{
"welcome_image": str(WELCOME_IMG_WIN),
"header_image": str(HEADER_IMG_WIN),
"icon_image": str(SPYREPO / "img_src" / "spyder.ico"),
"default_prefix": os.path.join(
"%LOCALAPPDATA%", INSTALLER_DEFAULT_PATH_STEM
),
"default_prefix_domain_user": os.path.join(
"%LOCALAPPDATA%", INSTALLER_DEFAULT_PATH_STEM
),
"default_prefix_all_users": os.path.join(
"%ALLUSERSPROFILE%", INSTALLER_DEFAULT_PATH_STEM
),
"check_path_length": False,
"post_install": str(RESOURCES / "post-install.bat"),
}
)
signing_certificate = os.environ.get("CONSTRUCTOR_SIGNING_CERTIFICATE")
if signing_certificate:
definitions["signing_certificate"] = signing_certificate
if definitions.get("welcome_image") or definitions.get("header_image"):
_generate_background_images(definitions.get("installer_type", "all"))
return definitions | build_installers.py | spyder.installers-conda | false | false | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 296 | 328 |
def _constructor():
"""
Create a temporary `construct.yaml` input file and
run `constructor`.
"""
constructor = find_executable("constructor")
if not constructor:
raise RuntimeError("Constructor must be installed and in PATH.")
definitions = _definitions()
cmd_args = [constructor, "-v", "--output-dir", str(DIST)]
if args.debug:
cmd_args.append("--debug")
conda_exe = os.environ.get("CONSTRUCTOR_CONDA_EXE")
if TARGET_PLATFORM and conda_exe:
cmd_args += ["--platform", TARGET_PLATFORM, "--conda-exe", conda_exe]
cmd_args.append(str(BUILD))
env = os.environ.copy()
env["CONDA_CHANNEL_PRIORITY"] = "strict"
logger.info("Command: " + " ".join(cmd_args))
logger.info("Configuration:")
yaml.dump(definitions, sys.stdout)
yaml.dump(definitions, BUILD / "construct.yaml")
check_call(cmd_args, env=env) | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 331 | 359 |
def licenses():
info_path = BUILD / "info.json"
try:
info = json.load(info_path)
except FileNotFoundError:
print(
"!! Use `constructor --debug` to write info.json and get licenses",
file=sys.stderr,
)
raise
zipname = BUILD / f"licenses.{OS}-{ARCH}.zip"
output_zip = zipfile.ZipFile(zipname, mode="w",
compression=zipfile.ZIP_DEFLATED)
output_zip.write(info_path)
for package_id, license_info in info["_licenses"].items():
package_name = package_id.split("::", 1)[1]
for license_type, license_files in license_info.items():
for i, license_file in enumerate(license_files, 1):
arcname = (f"{package_name}.{license_type.replace(' ', '_')}"
f".{i}.txt")
output_zip.write(license_file, arcname=arcname)
output_zip.close()
return zipname.resolve() | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 362 | 385 |
def main():
t0 = time()
try:
DIST.mkdir(exist_ok=True)
_constructor()
assert Path(OUTPUT_FILE).exists()
logger.info(f"Created {OUTPUT_FILE}")
finally:
elapse = timedelta(seconds=int(time() - t0))
logger.info(f"Build time: {elapse}")
if __name__ == "__main__":
if args.arch:
print(ARCH)
sys.exit()
if args.ext:
print(args.install_type)
sys.exit()
if args.artifact_name:
print(OUTPUT_FILE)
sys.exit()
if args.licenses:
print(licenses())
sys.exit()
if args.images:
_generate_background_images()
sys.exit()
main() | build_installers.py | spyder.installers-conda | false | true | [
"from argparse import ArgumentParser",
"from datetime import timedelta",
"from distutils.spawn import find_executable",
"from functools import partial",
"import json",
"from logging import getLogger",
"import os",
"from pathlib import Path",
"import platform",
"import re",
"from subprocess import check_call",
"import sys",
"from textwrap import dedent, indent",
"from time import time",
"import zipfile",
"from ruamel.yaml import YAML",
"from build_conda_pkgs import HERE, BUILD, RESOURCES, SPECS, h, get_version",
"from PIL import Image"
] | 388 | 417 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
spyder.py3compat
----------------
Transitional module providing compatibility functions intended to help
migrating from Python 2 to Python 3.
"""
import operator
import pickle # noqa. For compatibility with spyder-line-profiler
#==============================================================================
# Data types
#==============================================================================
# Python 3
TEXT_TYPES = (str,)
INT_TYPES = (int,)
#==============================================================================
# Strings
#==============================================================================
def is_type_text_string(obj):
"""Return True if `obj` is type text string, False if it is anything else,
like an instance of a class that extends the basestring class."""
return type(obj) in [str, bytes]
def is_text_string(obj):
"""Return True if `obj` is a text string, False if it is anything else,
like binary data (Python 3) or QString (PyQt API #1)"""
return isinstance(obj, str)
def is_binary_string(obj):
"""Return True if `obj` is a binary string, False if it is anything else"""
return isinstance(obj, bytes) | py3compat.py | spyder.spyder | false | true | [
"import operator",
"import pickle # noqa. For compatibility with spyder-line-profiler"
] | 1 | 42 |
def is_binary_string(obj):
"""Return True if `obj` is a binary string, False if it is anything else"""
return isinstance(obj, bytes)
def is_string(obj):
"""Return True if `obj` is a text or binary Python string object,
False if it is anything else, like a QString (PyQt API #1)"""
return is_text_string(obj) or is_binary_string(obj)
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if encoding is None:
return str(obj)
elif isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
else:
return str(obj, encoding)
def to_binary_string(obj, encoding='utf-8'):
"""Convert `obj` to binary string (bytes)"""
return bytes(obj, encoding)
#==============================================================================
# Misc.
#==============================================================================
def qbytearray_to_str(qba):
"""Convert QByteArray object to str in a way compatible with Python 3"""
return str(bytes(qba.toHex().data()).decode())
# =============================================================================
# Dict funcs
# =============================================================================
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw)) | py3compat.py | spyder.spyder | false | true | [
"import operator",
"import pickle # noqa. For compatibility with spyder-line-profiler"
] | 40 | 80 |
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
viewkeys = operator.methodcaller("keys")
viewvalues = operator.methodcaller("values")
viewitems = operator.methodcaller("items")
if __name__ == '__main__':
pass | py3compat.py | spyder.spyder | false | true | [
"import operator",
"import pickle # noqa. For compatibility with spyder-line-profiler"
] | 73 | 93 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""
Import guiqwt's pyplot module or matplotlib's pyplot.
"""
try:
from guiqwt.pyplot import *
except Exception:
from matplotlib.pyplot import * | pyplot.py | spyder.spyder | false | false | [
"from guiqwt.pyplot import *",
"from matplotlib.pyplot import *"
] | 1 | 18 |
# -*- coding: utf-8 -*-
"""
MIT License
===========
The spyder/images dir and some source files under other terms (see NOTICE.txt).
Copyright (c) 2009- Spyder Project Contributors and others (see AUTHORS.txt)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
version_info = (6, 0, 0, "dev0") | __init__.py | spyder.spyder | false | false | [
"import os",
"import sys",
"import platform",
"import qtpy",
"import qtpy.QtCore",
"from spyder.utils.conda import is_conda_env",
"from spyder.config.base import is_conda_based_app",
"from spyder.utils import vcs"
] | 1 | 32 |
version_info = (6, 0, 0, "dev0")
__version__ = '.'.join(map(str, version_info))
__installer_version__ = __version__
__title__ = 'Spyder'
__author__ = 'Spyder Project Contributors and others'
__license__ = __doc__
__project_url__ = 'https://github.com/spyder-ide/spyder'
__forum_url__ = 'https://groups.google.com/group/spyderlib'
__trouble_url__ = 'https://tinyurl.com/spyder-first-steps'
__trouble_url_short__ = 'https://tinyurl.com/SpyderHelp'
__website_url__ = 'https://www.spyder-ide.org/'
__docs_url__ = 'https://docs.spyder-ide.org/'
# Dear (Debian, RPM, ...) package makers, please feel free to customize the
# following path to module's data (images) and translations:
DATAPATH = LOCALEPATH = DOCPATH = MATHJAXPATH = JQUERYPATH = ''
import os
# Directory of the current file
__current_directory__ = os.path.dirname(os.path.abspath(__file__)) | __init__.py | spyder.spyder | false | false | [
"import os",
"import sys",
"import platform",
"import qtpy",
"import qtpy.QtCore",
"from spyder.utils.conda import is_conda_env",
"from spyder.config.base import is_conda_based_app",
"from spyder.utils import vcs"
] | 32 | 53 |
def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
from spyder.utils.conda import is_conda_env
from spyder.config.base import is_conda_based_app
revision = branch = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(
os.path.dirname(__current_directory__)
)
if is_conda_based_app():
installer = 'standalone'
elif is_conda_env(pyexec=sys.executable):
installer = 'conda'
else:
installer = 'pip'
versions = {
'spyder': __version__,
'installer': installer,
'python': platform.python_version(), # "2.7.3"
'bitness': 64 if sys.maxsize > 2**32 else 32,
'qt': qtpy.QtCore.__version__,
'qt_api': qtpy.API_NAME, # PyQt5
'qt_api_ver': (qtpy.PYSIDE_VERSION if qtpy.API == "pyside2"
else qtpy.PYQT_VERSION),
'system': platform.system(), # Linux, Windows, ...
'release': platform.release(), # XP, 10.6, 2.2.0, etc.
'revision': revision, # '9fdf926eccce',
'branch': branch, # '4.x' or master,
'machine': platform.machine(), # 'arm64', 'x86_64', 'AMD64', ...
'platform': platform.platform(aliased=True),
}
if sys.platform == 'darwin':
versions.update(system='macOS', release=platform.mac_ver()[0]) | __init__.py | spyder.spyder | false | true | [
"import os",
"import sys",
"import platform",
"import qtpy",
"import qtpy.QtCore",
"from spyder.utils.conda import is_conda_env",
"from spyder.config.base import is_conda_based_app",
"from spyder.utils import vcs"
] | 56 | 98 |
return versions | __init__.py | spyder.spyder | false | false | [
"import os",
"import sys",
"import platform",
"import qtpy",
"import qtpy.QtCore",
"from spyder.utils.conda import is_conda_env",
"from spyder.config.base import is_conda_based_app",
"from spyder.utils import vcs"
] | -1 | -1 |
def get_versions_text(reporev=True):
"""Create string of version information for components used by Spyder"""
versions = get_versions(reporev=reporev)
# Get git revision for development version
revision = versions['revision'] or ''
return f"""\
* Spyder version: {versions['spyder']} {revision} ({versions['installer']})
* Python version: {versions['python']} {versions['bitness']}-bit
* Qt version: {versions['qt']}
* {versions['qt_api']} version: {versions['qt_api_ver']}
* Operating System: {versions['platform']}
""" | __init__.py | spyder.spyder | false | true | [
"import os",
"import sys",
"import platform",
"import qtpy",
"import qtpy.QtCore",
"from spyder.utils.conda import is_conda_env",
"from spyder.config.base import is_conda_based_app",
"from spyder.utils import vcs"
] | 103 | 116 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Module checking Spyder runtime dependencies"""
# Standard library imports
import os
import os.path as osp
import sys
# Local imports
from spyder.config.base import _, running_in_ci, is_conda_based_app
from spyder.utils import programs
HERE = osp.dirname(osp.abspath(__file__))
# Python 3.8
PY38 = sys.version_info[:2] == (3, 8)
# =============================================================================
# Kind of dependency
# =============================================================================
MANDATORY = 'mandatory'
OPTIONAL = 'optional'
PLUGIN = 'spyder plugins' | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 1 | 30 |
# =============================================================================
# Versions
# =============================================================================
# Hard dependencies
APPLAUNCHSERVICES_REQVER = '>=0.3.0'
ATOMICWRITES_REQVER = '>=1.2.0'
CHARDET_REQVER = '>=2.0.0'
CLOUDPICKLE_REQVER = '>=0.5.0'
COOKIECUTTER_REQVER = '>=1.6.0'
DIFF_MATCH_PATCH_REQVER = '>=20181111'
INTERVALTREE_REQVER = '>=3.0.2'
IPYTHON_REQVER = ">=8.12.2,<8.13.0" if PY38 else ">=8.13.0,<9.0.0,!=8.17.1"
JEDI_REQVER = '>=0.17.2,<0.20.0'
JELLYFISH_REQVER = '>=0.7'
JSONSCHEMA_REQVER = '>=3.2.0'
KEYRING_REQVER = '>=17.0.0'
NBCONVERT_REQVER = '>=4.0'
NUMPYDOC_REQVER = '>=0.6.0'
PARAMIKO_REQVER = '>=2.4.0'
PARSO_REQVER = '>=0.7.0,<0.9.0'
PEXPECT_REQVER = '>=4.4.0'
PICKLESHARE_REQVER = '>=0.4'
PSUTIL_REQVER = '>=5.3'
PYGMENTS_REQVER = '>=2.0'
PYLINT_REQVER = '>=2.5.0,<3.1'
PYLINT_VENV_REQVER = '>=3.0.2'
PYLSP_REQVER = '>=1.9.0,<1.10.0'
PYLSP_BLACK_REQVER = '>=1.2.0,<3.0.0'
PYLS_SPYDER_REQVER = '>=0.4.0'
PYUCA_REQVER = '>=1.2'
PYXDG_REQVER = '>=0.26'
PYZMQ_REQVER = '>=22.1.0'
QDARKSTYLE_REQVER = '>=3.2.0,<3.3.0'
QSTYLIZER_REQVER = '>=0.2.2'
QTAWESOME_REQVER = '>=1.2.1'
QTCONSOLE_REQVER = '>=5.5.0,<5.6.0'
QTPY_REQVER = '>=2.4.0'
RTREE_REQVER = '>=0.9.7'
SETUPTOOLS_REQVER = '>=49.6.0'
SPHINX_REQVER = '>=0.6.6'
SPYDER_KERNELS_REQVER = '>=3.0.0b2,<3.0.0b3'
SUPERQT_REQVER = '>=0.6.1,<1.0.0'
TEXTDISTANCE_REQVER = '>=4.2.0'
THREE_MERGE_REQVER = '>=0.1.1'
WATCHDOG_REQVER = '>=0.10.3' | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 33 | 77 |
# Optional dependencies
CYTHON_REQVER = '>=0.21'
MATPLOTLIB_REQVER = '>=3.0.0'
NUMPY_REQVER = '>=1.7'
PANDAS_REQVER = '>=1.1.1'
SCIPY_REQVER = '>=0.17.0'
SYMPY_REQVER = '>=0.7.3' | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 79 | 85 |
# =============================================================================
# Descriptions
# NOTE: We declare our dependencies in **alphabetical** order
# If some dependencies are limited to some systems only, add a 'display' key.
# See 'applaunchservices' for an example.
# =============================================================================
# List of descriptions
DESCRIPTIONS = [
{'modname': "applaunchservices",
'package_name': "applaunchservices",
'features': _("Notify macOS that Spyder can open Python files"),
'required_version': APPLAUNCHSERVICES_REQVER,
'display': sys.platform == "darwin" and not is_conda_based_app()},
{'modname': "atomicwrites",
'package_name': "atomicwrites",
'features': _("Atomic file writes in the Editor"),
'required_version': ATOMICWRITES_REQVER},
{'modname': "chardet",
'package_name': "chardet",
'features': _("Character encoding auto-detection for the Editor"),
'required_version': CHARDET_REQVER},
{'modname': "cloudpickle",
'package_name': "cloudpickle",
'features': _("Handle communications between kernel and frontend"),
'required_version': CLOUDPICKLE_REQVER},
{'modname': "cookiecutter",
'package_name': "cookiecutter",
'features': _("Create projects from cookiecutter templates"),
'required_version': COOKIECUTTER_REQVER},
{'modname': "diff_match_patch",
'package_name': "diff-match-patch", | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 88 | 118 |
'features': _("Create projects from cookiecutter templates"),
'required_version': COOKIECUTTER_REQVER},
{'modname': "diff_match_patch",
'package_name': "diff-match-patch",
'features': _("Compute text file diff changes during edition"),
'required_version': DIFF_MATCH_PATCH_REQVER},
{'modname': "intervaltree",
'package_name': "intervaltree",
'features': _("Compute folding range nesting levels"),
'required_version': INTERVALTREE_REQVER},
{'modname': "IPython",
'package_name': "IPython",
'features': _("IPython interactive python environment"),
'required_version': IPYTHON_REQVER},
{'modname': "jedi",
'package_name': "jedi",
'features': _("Main backend for the Python Language Server"),
'required_version': JEDI_REQVER},
{'modname': "jellyfish",
'package_name': "jellyfish",
'features': _("Optimize algorithms for folding"),
'required_version': JELLYFISH_REQVER},
{'modname': 'jsonschema',
'package_name': 'jsonschema',
'features': _('Verify if snippets files are valid'),
'required_version': JSONSCHEMA_REQVER},
{'modname': "keyring",
'package_name': "keyring",
'features': _("Save Github credentials to report internal "
"errors securely"),
'required_version': KEYRING_REQVER},
{'modname': "nbconvert",
'package_name': "nbconvert",
'features': _("Manipulate Jupyter notebooks in the Editor"), | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 115 | 148 |
'required_version': KEYRING_REQVER},
{'modname': "nbconvert",
'package_name': "nbconvert",
'features': _("Manipulate Jupyter notebooks in the Editor"),
'required_version': NBCONVERT_REQVER},
{'modname': "numpydoc",
'package_name': "numpydoc",
'features': _("Improve code completion for objects that use Numpy docstrings"),
'required_version': NUMPYDOC_REQVER},
{'modname': "paramiko",
'package_name': "paramiko",
'features': _("Connect to remote kernels through SSH"),
'required_version': PARAMIKO_REQVER,
'display': os.name == 'nt'},
{'modname': "parso",
'package_name': "parso",
'features': _("Python parser that supports error recovery and "
"round-trip parsing"),
'required_version': PARSO_REQVER},
{'modname': "pexpect",
'package_name': "pexpect",
'features': _("Stdio support for our language server client"),
'required_version': PEXPECT_REQVER},
{'modname': "pickleshare",
'package_name': "pickleshare",
'features': _("Cache the list of installed Python modules"),
'required_version': PICKLESHARE_REQVER},
{'modname': "psutil",
'package_name': "psutil",
'features': _("CPU and memory usage info in the status bar"),
'required_version': PSUTIL_REQVER},
{'modname': "pygments",
'package_name': "pygments",
'features': _("Syntax highlighting for a lot of file types in the Editor"), | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 145 | 178 |
'required_version': PSUTIL_REQVER},
{'modname': "pygments",
'package_name': "pygments",
'features': _("Syntax highlighting for a lot of file types in the Editor"),
'required_version': PYGMENTS_REQVER},
{'modname': "pylint",
'package_name': "pylint",
'features': _("Static code analysis"),
'required_version': PYLINT_REQVER},
{'modname': "pylint_venv",
'package_name': "pylint-venv",
'features': _("Use the same Pylint installation with different virtual"
" environments"),
'required_version': PYLINT_VENV_REQVER},
{'modname': 'pylsp',
'package_name': 'python-lsp-server',
'features': _("Code completion and linting for the Editor"),
'required_version': PYLSP_REQVER},
{'modname': 'pylsp_black',
'package_name': 'python-lsp-black',
'features': _("Autoformat Python files in the Editor with the Black "
"package"),
'required_version': PYLSP_BLACK_REQVER},
{'modname': 'pyls_spyder',
'package_name': 'pyls-spyder',
'features': _('Spyder plugin for the Python LSP Server'),
'required_version': PYLS_SPYDER_REQVER},
{'modname': 'pyuca',
'package_name': 'pyuca',
'features': _('Properly sort lists of non-English strings'),
'required_version': PYUCA_REQVER},
{'modname': "xdg",
'package_name': "pyxdg",
'features': _("Parse desktop files on Linux"),
'required_version': PYXDG_REQVER, | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 175 | 209 |
'required_version': PYUCA_REQVER},
{'modname': "xdg",
'package_name': "pyxdg",
'features': _("Parse desktop files on Linux"),
'required_version': PYXDG_REQVER,
'display': sys.platform.startswith('linux')},
{'modname': "zmq",
'package_name': "pyzmq",
'features': _("Client for the language server protocol (LSP)"),
'required_version': PYZMQ_REQVER},
{'modname': "qdarkstyle",
'package_name': "qdarkstyle",
'features': _("Dark style for the entire interface"),
'required_version': QDARKSTYLE_REQVER},
{'modname': "qstylizer",
'package_name': "qstylizer",
'features': _("Customize Qt stylesheets"),
'required_version': QSTYLIZER_REQVER},
{'modname': "qtawesome",
'package_name': "qtawesome",
'features': _("Icon theme based on FontAwesome and Material Design icons"),
'required_version': QTAWESOME_REQVER},
{'modname': "qtconsole",
'package_name': "qtconsole",
'features': _("Main package for the IPython console"),
'required_version': QTCONSOLE_REQVER},
{'modname': "qtpy",
'package_name': "qtpy",
'features': _("Abstraction layer for Python Qt bindings."),
'required_version': QTPY_REQVER},
{'modname': "rtree",
'package_name': "rtree",
'features': _("Fast access to code snippet regions"),
'required_version': RTREE_REQVER},
{'modname': "setuptools",
'package_name': "setuptools", | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 205 | 240 |
'package_name': "rtree",
'features': _("Fast access to code snippet regions"),
'required_version': RTREE_REQVER},
{'modname': "setuptools",
'package_name': "setuptools",
'features': _("Determine package versions"),
'required_version': SETUPTOOLS_REQVER},
{'modname': "sphinx",
'package_name': "sphinx",
'features': _("Show help for objects in the Editor and Consoles in a dedicated pane"),
'required_version': SPHINX_REQVER},
{'modname': "spyder_kernels",
'package_name': "spyder-kernels",
'features': _("Jupyter kernels for the Spyder console"),
'required_version': SPYDER_KERNELS_REQVER},
{'modname': "superqt",
'package_name': "superqt",
'features': _("Special widgets and utilities for PyQt applications"),
'required_version': SUPERQT_REQVER},
{'modname': 'textdistance',
'package_name': "textdistance",
'features': _('Compute distances between strings'),
'required_version': TEXTDISTANCE_REQVER},
{'modname': "three_merge",
'package_name': "three-merge",
'features': _("3-way merge algorithm to merge document changes"),
'required_version': THREE_MERGE_REQVER},
{'modname': "watchdog",
'package_name': "watchdog",
'features': _("Watch file changes on project directories"),
'required_version': WATCHDOG_REQVER},
] | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 236 | 267 |
# Optional dependencies
DESCRIPTIONS += [
{'modname': "cython",
'package_name': "cython",
'features': _("Run Cython files in the IPython Console"),
'required_version': CYTHON_REQVER,
'kind': OPTIONAL},
{'modname': "matplotlib",
'package_name': "matplotlib",
'features': _("2D/3D plotting in the IPython console"),
'required_version': MATPLOTLIB_REQVER,
'kind': OPTIONAL},
{'modname': "numpy",
'package_name': "numpy",
'features': _("View and edit two and three dimensional arrays in the Variable Explorer"),
'required_version': NUMPY_REQVER,
'kind': OPTIONAL},
{'modname': 'pandas',
'package_name': 'pandas',
'features': _("View and edit DataFrames and Series in the Variable Explorer"),
'required_version': PANDAS_REQVER,
'kind': OPTIONAL},
{'modname': "scipy",
'package_name': "scipy",
'features': _("Import Matlab workspace files in the Variable Explorer"),
'required_version': SCIPY_REQVER,
'kind': OPTIONAL},
{'modname': "sympy",
'package_name': "sympy",
'features': _("Symbolic mathematics in the IPython Console"),
'required_version': SYMPY_REQVER,
'kind': OPTIONAL}
]
# =============================================================================
# Code
# ============================================================================= | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 270 | 307 |
class Dependency(object):
"""
Spyder's dependency
Version may starts with =, >=, > or < to specify the exact requirement;
multiple conditions may be separated by ',' (e.g. '>=0.13,<1.0')"""
OK = 'OK'
NOK = 'NOK'
def __init__(self, modname, package_name, features, required_version,
installed_version=None, kind=MANDATORY):
self.modname = modname
self.package_name = package_name
self.features = features
self.required_version = required_version
self.kind = kind
# Although this is not necessarily the case, it's customary that a
# package's distribution name be it's name on PyPI with hyphens
# replaced by underscores.
# Example:
# * Package name: python-lsp-black.
# * Distribution name: python_lsp_black
self.distribution_name = self.package_name.replace('-', '_') | dependencies.py | spyder.spyder | false | false | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 308 | 332 |
if installed_version is None:
try:
self.installed_version = programs.get_module_version(modname)
if not self.installed_version:
# Use get_package_version and the distribution name
# because there are cases for which the version can't
# be obtained from the module (e.g. pylsp_black).
self.installed_version = programs.get_package_version(
self.distribution_name)
except Exception:
# NOTE: Don't add any exception type here!
# Modules can fail to import in several ways besides
# ImportError
self.installed_version = None
else:
self.installed_version = installed_version
def check(self):
"""Check if dependency is installed"""
if self.modname == 'spyder_kernels':
# TODO: Remove when spyder-kernels 3 is released!
return True
if self.required_version:
installed = programs.is_module_installed(
self.modname,
self.required_version,
distribution_name=self.distribution_name
)
return installed
else:
return True | dependencies.py | spyder.spyder | false | true | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 334 | 364 |
def get_installed_version(self):
"""Return dependency status (string)"""
if self.check():
return '%s (%s)' % (self.installed_version, self.OK)
else:
return '%s (%s)' % (self.installed_version, self.NOK)
def get_status(self):
"""Return dependency status (string)"""
if self.check():
return self.OK
else:
return self.NOK
DEPENDENCIES = [] | dependencies.py | spyder.spyder | false | true | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 366 | 381 |
def add(modname, package_name, features, required_version,
installed_version=None, kind=MANDATORY):
"""Add Spyder dependency"""
global DEPENDENCIES
for dependency in DEPENDENCIES:
# Avoid showing an unnecessary error when running our tests.
if running_in_ci() and 'spyder_boilerplate' in modname:
continue
if dependency.modname == modname:
raise ValueError(
f"Dependency has already been registered: {modname}")
DEPENDENCIES += [Dependency(modname, package_name, features,
required_version,
installed_version, kind)]
def check(modname):
"""Check if required dependency is installed"""
for dependency in DEPENDENCIES:
if dependency.modname == modname:
return dependency.check()
else:
raise RuntimeError("Unknown dependency %s" % modname) | dependencies.py | spyder.spyder | false | true | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 384 | 408 |
def status(deps=DEPENDENCIES, linesep=os.linesep):
"""Return a status of dependencies."""
maxwidth = 0
data = []
# Find maximum width
for dep in deps:
title = dep.modname
if dep.required_version is not None:
title += ' ' + dep.required_version
maxwidth = max([maxwidth, len(title)])
dep_order = {MANDATORY: '0', OPTIONAL: '1', PLUGIN: '2'}
order_dep = {'0': MANDATORY, '1': OPTIONAL, '2': PLUGIN}
data.append([dep_order[dep.kind], title, dep.get_installed_version()])
# Construct text and sort by kind and name
maxwidth += 1
text = ""
prev_order = '-1'
for order, title, version in sorted(
data, key=lambda x: x[0] + x[1].lower()):
if order != prev_order:
name = order_dep[order]
if name == MANDATORY:
text += f'# {name.capitalize()}:{linesep}'
else:
text += f'{linesep}# {name.capitalize()}:{linesep}'
prev_order = order
text += f'{title.ljust(maxwidth)}: {version}{linesep}'
# Remove spurious linesep when reporting deps to Github
if not linesep == '<br>':
text = text[:-1]
return text | dependencies.py | spyder.spyder | false | true | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 411 | 447 |
def missing_dependencies():
"""Return the status of missing dependencies (if any)"""
missing_deps = []
for dependency in DEPENDENCIES:
if dependency.kind != OPTIONAL and not dependency.check():
missing_deps.append(dependency)
if missing_deps:
return status(deps=missing_deps, linesep='<br>')
else:
return ""
def declare_dependencies():
for dep in DESCRIPTIONS:
if dep.get('display', True):
add(dep['modname'], dep['package_name'],
dep['features'], dep['required_version'],
kind=dep.get('kind', MANDATORY)) | dependencies.py | spyder.spyder | false | true | [
"import os",
"import os.path as osp",
"import sys",
"from spyder.config.base import _, running_in_ci, is_conda_based_app",
"from spyder.utils import programs"
] | 450 | 468 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Module checking Spyder installation requirements"""
# Third-party imports
from packaging.version import parse
def show_warning(message):
"""Show warning using Tkinter if available"""
try:
# If tkinter is installed (highly probable), show an error pop-up.
# From https://stackoverflow.com/a/17280890/438386
import tkinter as tk
root = tk.Tk()
root.title("Spyder")
label = tk.Label(root, text=message, justify='left')
label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
button = tk.Button(root, text="OK", command=root.destroy)
button.pack(side="bottom", fill="none", expand=True)
root.mainloop()
except Exception:
pass
raise RuntimeError(message) | requirements.py | spyder.spyder | false | true | [
"from packaging.version import parse",
"import tkinter as tk",
"import qtpy",
"show_warning(\"Failed to import qtpy.\\n\""
] | 1 | 29 |
def check_qt():
"""Check Qt binding requirements"""
qt_infos = dict(
pyqt5=("PyQt5", "5.15"),
pyside2=("PySide2", "5.15"),
pyqt6=("PyQt6", "6.5"),
pyside6=("PySide6", "6.5")
)
try:
import qtpy
package_name, required_ver = qt_infos[qtpy.API]
actual_ver = qtpy.QT_VERSION
if (
actual_ver is None
or parse(actual_ver) < parse(required_ver)
):
show_warning("Please check Spyder installation requirements:\n"
"%s %s+ is required (found %s)."
% (package_name, required_ver, actual_ver))
except ImportError:
show_warning("Failed to import qtpy.\n"
"Please check Spyder installation requirements:\n\n"
"qtpy 1.2.0+ and\n"
"%s %s+\n\n"
"are required to run Spyder."
% (qt_infos['pyqt5'])) | requirements.py | spyder.spyder | false | true | [
"from packaging.version import parse",
"import tkinter as tk",
"import qtpy",
"show_warning(\"Failed to import qtpy.\\n\""
] | 32 | 59 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
r"""
Patching PIL (Python Imaging Library) to avoid triggering the error:
AccessInit: hash collision: 3 for both 1 and 1
This error is occurring because of a bug in the PIL import mechanism.
How to reproduce this bug in a standard Python interpreter outside Spyder?
By importing PIL by two different mechanisms
Example on Windows:
===============================================================================
C:\Python27\Lib\site-packages>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> from PIL import Image
AccessInit: hash collision: 3 for both 1 and 1
=============================================================================== | pil_patch.py | spyder.spyder | false | false | [
"This error is occurring because of a bug in the PIL import mechanism.",
">>> import Image",
">>> from PIL import Image",
">>> import scipy",
">>> from pylab import *",
">>> import Image",
">>> import PIL",
">>> from PIL import Image",
"from PIL import Image",
"import PIL",
"import Image",
"import PIL"
] | 1 | 24 |
Another example on Windows (actually that's the same, but this is the exact
case encountered with Spyder when the global working directory is the
site-packages directory):
===============================================================================
C:\Python27\Lib\site-packages>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
>>> from pylab import *
AccessInit: hash collision: 3 for both 1 and 1
===============================================================================
The solution to this fix is the following patch:
===============================================================================
C:\Python27\Lib\site-packages>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> import PIL
>>> PIL.Image = Image
>>> from PIL import Image
>>>
===============================================================================
"""
try:
# For Pillow compatibility
from PIL import Image
import PIL
PIL.Image = Image
except ImportError:
# For PIL
import Image
import PIL
PIL.Image = Image | pil_patch.py | spyder.spyder | false | false | [
"This error is occurring because of a bug in the PIL import mechanism.",
">>> import Image",
">>> from PIL import Image",
">>> import scipy",
">>> from pylab import *",
">>> import Image",
">>> import PIL",
">>> from PIL import Image",
"from PIL import Image",
"import PIL",
"import Image",
"import PIL"
] | 26 | 61 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Spyder API Version.
The API version should be modified according to the following rules:
1. If a module/class/method/function is added, then the minor version
must be increased.
2. If a module/class/method/function is removed, renamed or changes its
signature, then the major version must be increased.
3. Whenever possible, deprecation marks and alerts should be employed in
order to inform developers of breaking-compatibility changes in a
future API release. In such case, the minor version should be increased
and once the deprecated APIs disappear then the major version should be
updated.
"""
VERSION_INFO = (0, 10, 0)
__version__ = '.'.join(map(str, VERSION_INFO)) | _version.py | spyder.spyder.api | false | false | [] | 1 | 26 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
spyder.api
==========
This package contains base classes, mixins and widgets that can be used
to create third-party plugins to extend Spyder.
This API should be considered pre-release and is subject to change
before its version reaches 1.0.
"""
from ._version import __version__ | __init__.py | spyder.spyder.api | false | false | [
"from ._version import __version__"
] | 1 | 18 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
API to create an entry in Spyder Preferences associated to a given plugin.
"""
# Standard library imports
import types
from typing import Set
# Local imports
from spyder.config.manager import CONF
from spyder.config.types import ConfigurationKey
from spyder.api.utils import PrefixedTuple
from spyder.plugins.preferences.widgets.config_widgets import (
SpyderConfigPage,
BaseConfigTab
)
OptionSet = Set[ConfigurationKey] | preferences.py | spyder.spyder.api | false | false | [
"import types",
"from typing import Set",
"from spyder.config.manager import CONF",
"from spyder.config.types import ConfigurationKey",
"from spyder.api.utils import PrefixedTuple",
"from spyder.plugins.preferences.widgets.config_widgets import ("
] | 1 | 25 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 16