Best Python code snippet using ATX
external.py
Source:external.py
1######################################################################2# EXTERNAL #3######################################################################4import utils5from Classes.PathManager import PathManager6from urllib.request import urlretrieve7from Classes.Metadata import Metadata8from subprocess import PIPE, Popen9from extension import write10from halo import Halo11from colorama import Fore12import json as js13import mslex14import sys15import os16import click17def handle_python_package(package_name: str, version: str, mode: str, metadata: Metadata):18 """19 Installs a python package handling metadata for the method20 #### Arguments21 package_name (str): The name of the python package to be installed22 version (str): The version of the python package to be installed23 mode (str): The method (installation/uninstallation)24 metadata (`Metadata`): Metadata for the method25 """26 command = ''27 valid = Popen(mslex.split('pip --version'),28 stdin=PIPE, stdout=PIPE, stderr=PIPE)29 _, err = valid.communicate()30 if err:31 click.echo(click.style(32 'Python Is Not Installed. Exit Code [0011]', fg='red'))33 utils.disp_error_msg(utils.get_error_message(34 '0011', 'install', package_name, None, metadata, package_name), metadata)35 utils.handle_exit('ERROR', None, metadata)36 if mode == 'install':37 command = 'python -m pip install --upgrade --no-input'38 command += f' {package_name}'39 if version != 'latest':40 command += f'=={version}'41 proc = Popen(mslex.split(command), stdin=PIPE,42 stdout=PIPE, stderr=PIPE)43 py_version = sys.version.split()44 for line in proc.stdout:45 line = line.decode('utf-8')46 if f'Collecting {package_name}' in line:47 write(48 f'Python v{py_version[0]} :: Collecting {package_name}', 'bright_green', metadata)49 if 'Downloading' in line and package_name in line:50 write(51 f'Python v{py_version[0]} :: Downloading {package_name}', 'bright_green', metadata)52 if 'Installing collected packages' in line and package_name in line:53 write(54 f'Python v{py_version[0]} :: Installing {package_name}', 'bright_green', metadata)55 if f'Requirement ' in line and package_name in line:56 write(57 f'Python v{py_version[0]} :: {package_name} Is Already Installed And On The Latest Version ==> {line.split()[-1]}', 'bright_yellow', metadata)58 break59 if 'Successfully installed' in line and package_name in line:60 ver = line.split('-')[1]61 write(62 f'Python v{py_version[0]} :: Successfully Installed {package_name} {ver}', 'bright_green', metadata)63 if 'You should consider upgrading via' in line:64 wants = utils.confirm(65 'Would you like to upgrade your pip version?')66 if wants:67 write('Updating Pip Version', 'bright_green', metadata)68 Popen(mslex.split('python -m pip install --upgrade pip'))69 elif mode == 'uninstall':70 command = 'python -m pip uninstall --no-input --yes'71 command += f' {package_name}'72 if version:73 command += f'=={version}'74 proc = Popen(mslex.split(command), stdin=PIPE,75 stdout=PIPE, stderr=PIPE)76 py_version = sys.version.split()77 for line in proc.stdout:78 line = line.decode('utf-8')79 if 'Uninstalling' in line and package_name in line:80 write(81 f'Python v{py_version[0]} :: Uninstalling {package_name}', 'bright_green', metadata)82 if 'Successfully uninstalled' in line and package_name in line:83 ver = line.split('-')[1]84 write(85 f'Python v{py_version[0]} :: Successfully Uninstalled {package_name} {ver}', 'bright_green', metadata)86 _, err = proc.communicate()87 if err:88 err = err.decode('utf-8')89 if f'WARNING: Skipping {package_name}' in err:90 write(91 f'Python v{py_version[0]} :: Could Not Find Any Installations Of {package_name}', 'bright_yellow', metadata)92def handle_node_package(package_name: str, mode: str, requested_version: str, metadata: Metadata):93 """94 Installs a node/npm package handling metadata for the method95 #### Arguments96 package_name (`str`): The name of the node/npm package to be installed97 version (`str`): The version of the node/npm package to be installed98 mode (`str`): The method (installation/uninstallation)99 metadata (`Metadata`): Metadata for the method100 """101 version_proc = Popen(mslex.split('npm --version'),102 stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)103 version, err = version_proc.communicate()104 version = version.decode().strip()105 if err:106 click.echo(click.style(107 'npm Or node Is Not Installed. Exit Code [0011]', fg='bright_yellow'))108 utils.disp_error_msg(utils.get_error_message(109 '0011', 'install', package_name, None, metadata, package_name), metadata)110 utils.handle_exit('ERROR', None, metadata)111 if mode == 'install':112 add_str = f"@{requested_version}" if requested_version else ""113 command = f'npm i {package_name} -g' + add_str114 proc = Popen(mslex.split(command), stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)115 write(f'npm v{version} :: Collecting {package_name}',116 'bright_green', metadata)117 package_version = None118 for line in proc.stdout:119 line = line.decode()120 if 'node install.js' in line:121 write(122 f'npm v{version} :: Running `node install.js` for {package_name}', 'bright_green', metadata)123 if package_name in line and '@' in line and 'install' in line or ' postinstall' in line:124 package_version = line.split()[1]125 write(126 f'npm v{version} :: {package_version} Installing To <=> "{line.split()[3]}"', 'bright_green', metadata)127 if 'Success' in line and package_name in line or 'added' in line:128 write(129 f'npm v{version} :: Successfully Installed {package_version}', 'bright_green', metadata)130 elif package_name in line and '@' in line:131 package_version = line.replace(132 '+ ', '').replace(package_name, '').strip()133 if 'updated' in line:134 if package_version:135 write(136 f'npm v{version} :: Sucessfully Updated {package_name}{package_version}', 'bright_green', metadata)137 else:138 write(139 f'npm v{version} :: Sucessfully Updated {package_name}', 'bright_green', metadata)140 else:141 add_str = f"@{requested_version}" if requested_version else ""142 command = f'npm uninstall {package_name} -g' + add_str143 proc = Popen(mslex.split(command), stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)144 for line in proc.stdout:145 line = line.decode()146 if 'audited' in line and 'packages' in line:147 number = line.split()[1].strip()148 time = line.split()[4].strip()149 write(f'npm v{version} :: Successfully Uninstalled {package_name} and {number} Other Dependencies in {time}', 'bright_green', metadata)150 if 'up to date' in line:151 write(152 f'npm v{version} :: Could Not Find Any Existing Installations Of {package_name}', 'bright_yellow', metadata)153 if 'removed' in line:154 print(line)155 number = line.split(' ')[1].strip()156 time = line.split(' ')[4].strip()157 write(158 f'npm v{version} :: Sucessfully Uninstalled {package_name} And {number} Other Dependencies in {time}', 'bright_green', metadata)159def handle_vscode_extension(package_name: str, requested_version: str, mode: str, metadata: Metadata):160 """161 Installs a visual studio code package handling metadata for the method162 #### Arguments163 package_name (str): The name of the visual studio code package to be installed164 version (str): The version of the visual studio code package to be installed165 mode (str): The method (installation/uninstallation)166 metadata (`Metadata`): Metadata for the method167 """168 169 base_c = 'code'170 output = Popen(mslex.split('code --version'), stdin=PIPE,171 stdout=PIPE, stderr=PIPE, shell=True)172 version, _ = output.communicate()173 version = version.decode()174 if output.returncode != 0:175 output = Popen(mslex.split('code-insiders --version'),176 stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)177 version, _ = output.communicate()178 version = version.decode()179 base_c = 'code-insiders'180 if output.returncode != 0:181 click.echo(click.style(182 'Visual Studio Code Or vscode Is Not Installed. Exit Code [0111]', fg='bright_yellow'))183 utils.disp_error_msg(utils.get_error_message(184 '0111', 'install', package_name, None, metadata, package_name), metadata)185 utils.handle_exit('error', '', metadata)186 version = version.strip().split('\n')[0]187 if mode == 'install':188 add_str = f"@{requested_version}" if requested_version else ""189 command = f'{base_c} --install-extension {package_name}{add_str} --force'190 proc = Popen(mslex.split(command), stdin=PIPE,191 stdout=PIPE, stderr=PIPE, shell=True)192 success = False193 for line in proc.stdout:194 line = line.decode()195 if 'Installing extensions' in line:196 if metadata.no_color:197 write(198 f'Code v{version} :: Installing {package_name}', 'white', metadata)199 else:200 write(201 f'Code v{version} :: Installing {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.RESET}', 'bright_green', metadata)202 203 if 'is already installed' in line:204 success = True205 if metadata.no_color:206 write(207 f'Code v{version} :: {package_name} Is Already Installed!', 'white', metadata)208 else:209 write(210 f'{Fore.LIGHTGREEN_EX}Code v{version} :: {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.LIGHTYELLOW_EX} Is Already Installed!', 'white', metadata)211 212 if 'was successfully installed' in line:213 if metadata.no_color:214 write(215 f'Code v{version} :: Successfully Installed {package_name}', 'white', metadata)216 success = True217 else:218 write(219 f'{Fore.LIGHTGREEN_EX}Code v{version} :: Successfully Installed {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.RESET}', 'bright_green', metadata)220 if not success:221 write(222 f'{Fore.LIGHTGREEN_EX}Code v{version} :: Successfully Installed {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.RESET}', 'bright_green', metadata)223 if mode == 'uninstall':224 add_str = f"@{requested_version}" if requested_version else ""225 command = f'{base_c} --uninstall-extension {package_name}{add_str} --force'226 proc = Popen(mslex.split(command), stdin=PIPE,227 stdout=PIPE, stderr=PIPE, shell=True)228 for line in proc.stdout:229 line = line.decode()230 231 if 'Uninstalling' in line:232 if metadata.no_color:233 write(f'Code v{version} :: Uninstalling {package_name}', 'white', metadata)234 else:235 write(236 f'Code v{version} :: Uninstalling {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.RESET}', 'bright_green', metadata)237 if 'is not installed' in line:238 if metadata.no_color:239 write(f'Code v{version} :: {package_name} is not installed!', 'white', metadata)240 else:241 write(f'{Fore.LIGHTGREEN_EX}Code v{version} :: {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.LIGHTYELLOW_EX} is not installed!', 'white', metadata)242 if 'was successfully uninstalled' in line:243 if metadata.no_color:244 write(f'Code v{version} :: Successfully Uninstalled {package_name}', 'white', metadata)245 else:246 write(f'{Fore.LIGHTGREEN_EX}Code v{version} :: Successfully Uninstalled {Fore.LIGHTMAGENTA_EX}{package_name}{Fore.RESET}', 'bright_green', metadata)247def handle_sublime_extension(package_name: str, mode: str, metadata: Metadata):248 """249 Installs a sublime text package handling metadata for the method250 #### Arguments251 package_name (str): The name of the sublime text package to be installed252 version (str): The version of the sublime text package to be installed253 mode (str): The method (installation/uninstallation)254 metadata (`Metadata`): Metadata for the method255 """256 if mode != 'install':257 return258 if utils.find_existing_installation('sublime-text-3', 'Sublime Text 3'):259 location = PathManager.get_appdata_directory().replace('\electric', '') + \260 '\Sublime Text 3'261 if os.path.isdir(location) and os.path.isfile(fr'{location}\Packages\User\Package Control.sublime-settings'):262 with open(fr'{location}\Packages\User\Package Control.sublime-settings', 'r') as f:263 lines = f.readlines()264 idx = 0265 for line in lines:266 if '"Package Control",' in line.strip():267 idx = lines.index(line)268 if ']' in lines[idx + 1].strip():269 lines[idx] = " \"Package Control\""270 with open(fr'{location}\Packages\User\Package Control.sublime-settings', 'w') as f:271 f.writelines(lines)272 with open(fr'{location}\Packages\User\Package Control.sublime-settings', 'r') as f:273 json = js.load(f)274 current_packages = json['installed_packages']275 if package_name in current_packages:276 write(f'{package_name} Is Already Installed!',277 'white', metadata)278 sys.exit()279 current_packages.append(package_name)280 updated_packages = current_packages281 del json['installed_packages']282 json['installed_packages'] = updated_packages283 with open(fr'{location}\Packages\User\Package Control.sublime-settings', 'w+') as f:284 f.write(js.dumps(json, indent=4))285 write(286 f'Successfully Added {package_name} to Sublime Text 3', 'white', metadata)287 else:288 if not os.path.isdir(location):289 os.mkdir(location)290 if not os.path.isdir(fr'{location}\Installed Packages'):291 os.mkdir(fr'{location}\Installed Packages')292 # Package Control Not Installed293 with Halo('Installing Package Control', text_color='cyan'):294 urlretrieve('https://packagecontrol.io/Package%20Control.sublime-package',295 fr'{location}\Installed Packages\Package Control.sublime-package')296 if not os.path.isdir(fr'{location}\Packages'):297 os.mkdir(fr'{location}\Packages')298 if not os.path.isdir(fr'{location}\Packages\User'):299 os.mkdir(fr'{location}\Packages\User')300 with open(fr'{location}\Packages\User\Package Control.sublime-settings', 'w+') as f:301 f.write(302 js.dumps({303 "bootstrapped": True,304 "installed_packages": [305 "Package Control"306 ]},307 indent=4308 )309 )310 handle_sublime_extension(package_name, mode, metadata)311 else:312 click.echo(click.style(313 'Sublime Text 3 Is Not Installed. Exit Code [0112]', fg='bright_yellow'))314 utils.disp_error_msg(utils.get_error_message(315 '0112', 'install', package_name, None, metadata, package_name), metadata)316 utils.handle_exit('error', '', metadata)317def handle_atom_package(package_name: str, mode: str, requested_version: str, metadata: Metadata):318 """319 Installs an atom package handling metadata320 #### Arguments321 package_name (str): The name of the atom package to be installed322 version (str): The version of the atom package to be installed323 mode (str): The method (installation/uninstallation)324 metadata (`Metadata`): Metadata for the method325 """326 if mode == 'install':327 proc = Popen('apm'.split(),328 stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)329 proc.communicate()330 if proc.returncode != 0:331 click.echo(click.style('Atom Is Not Installed. Exit Code [0113]', fg='bright_yellow'))332 utils.disp_error_msg(utils.get_error_message('0113', 'install', package_name, None, metadata, package_name), metadata)333 utils.handle_exit('error', '', metadata)334 with Halo(f'apm :: Installing {package_name}', text_color='cyan') as h:335 add_str = f"@{requested_version}" if requested_version else ""336 command = f'apm install {package_name}' + add_str337 proc = Popen(338 command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)339 340 for line in proc.stdout:341 line = line.decode()342 if 'failed' in line:343 h.fail(344 f' Failed to Install {package_name} to <=> {line.split()[3]}')345 if 'done' in line:346 h.stop()347 click.echo(click.style(348 f' Successfully Installed {package_name} to <=> {line.split()[3]}', 'bright_green'))349 if mode == 'uninstall':350 proc = Popen('apm'.split(),351 stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)352 proc.communicate()353 if proc.returncode != 0:354 click.echo(click.style('Atom Is Not Installed. Exit Code [0113]', fg='bright_yellow'))355 utils.disp_error_msg(utils.get_error_message('0113', 'install', package_name, None, metadata, package_name), metadata)356 utils.handle_exit('error', '', metadata)357 with Halo(f'apm :: Uninstalling {package_name}', text_color='cyan') as h:358 add_str = f"@{requested_version}" if requested_version else ""359 command = f'apm deinstall {package_name}' + add_str360 proc = Popen(361 command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)362 for line in proc.stdout:363 line = line.decode()364 365 if 'failed' in line:366 h.fail(f' Failed to Uninstall {package_name}')367 if 'done' in line:368 h.stop()369 click.echo(click.style(...
dependencies.py
Source:dependencies.py
1# -*- coding: utf-8 -*-2#3# Copyright © Spyder Project Contributors4# Licensed under the terms of the MIT License5# (see spyder/__init__.py for details)6"""Module checking Spyder runtime dependencies"""7import os8import sys9# Local imports10from spyder.utils import programs11from spyder.config.base import _12from spyder.config.utils import is_anaconda13from spyder.py3compat import PY214# =============================================================================15# Kind of dependency16# =============================================================================17MANDATORY = 'mandatory'18OPTIONAL = 'optional'19PLUGIN = 'spyder plugins'20# =============================================================================21# Versions22# =============================================================================23# Hard dependencies24APPLAUNCHSERVICES_REQVER = '>=0.1.7'25ATOMICWRITES_REQVER = '>=1.2.0'26CHARDET_REQVER = '>=2.0.0'27CLOUDPICKLE_REQVER = '>=0.5.0'28COOKIECUTTER_REQVER = '>=1.6.0'29DIFF_MATCH_PATCH_REQVER = '>=20181111'30INTERVALTREE_REQVER = None31IPYTHON_REQVER = ">=4.0;<6.0" if PY2 else ">=4.0"32JEDI_REQVER = '=0.17.1'33KEYRING_REQVER = None34NBCONVERT_REQVER = '>=4.0'35NUMPYDOC_REQVER = '>=0.6.0'36PARAMIKO_REQVER = '>=2.4.0'37PARSO_REQVER = '=0.7.0'38PEXPECT_REQVER = '>=4.4.0'39PICKLESHARE_REQVER = '>=0.4'40PSUTIL_REQVER = '>=5.3'41PYGMENTS_REQVER = '>=2.0'42PYLINT_REQVER = '>=1.0'43PYLS_REQVER = '>=0.34.0;<1.0.0'44PYXDG_REQVER = '>=0.26'45PYZMQ_REQVER = '>=17'46QDARKSTYLE_REQVER = '>=2.8'47QTAWESOME_REQVER = '>=0.5.7'48QTCONSOLE_REQVER = '>=4.6.0'49QTPY_REQVER = '>=1.5.0'50RTREE_REQVER = '>=0.8.3'51SPHINX_REQVER = '>=0.6.6'52SPYDER_KERNELS_REQVER = '>=2.0.0dev0'53WATCHDOG_REQVER = None54# Optional dependencies55CYTHON_REQVER = '>=0.21'56MATPLOTLIB_REQVER = '>=2.0.0'57NUMPY_REQVER = '>=1.7'58PANDAS_REQVER = '>=0.13.1'59SCIPY_REQVER = '>=0.17.0'60SYMPY_REQVER = '>=0.7.3'61# =============================================================================62# Descriptions63# NOTE: We declare our dependencies in **alphabetical** order64# If some dependencies are limited to some systems only, add a 'display' key.65# See 'applaunchservices' for an example.66# =============================================================================67# List of descriptions68DESCRIPTIONS = [69 {'modname': "applaunchservices",70 'package_name': "applaunchservices",71 'features': _("Notify macOS that Spyder can open Python files"),72 'required_version': APPLAUNCHSERVICES_REQVER,73 'display': sys.platform == "darwin"},74 {'modname': "atomicwrites",75 'package_name': "atomicwrites",76 'features': _("Atomic file writes in the Editor"),77 'required_version': ATOMICWRITES_REQVER},78 {'modname': "chardet",79 'package_name': "chardet",80 'features': _("Character encoding auto-detection for the Editor"),81 'required_version': CHARDET_REQVER},82 {'modname': "cloudpickle",83 'package_name': "cloudpickle",84 'features': _("Handle communications between kernel and frontend"),85 'required_version': CLOUDPICKLE_REQVER},86 {'modname': "cookiecutter",87 'package_name': "cookiecutter",88 'features': _("Create projects from cookiecutter templates"),89 'required_version': COOKIECUTTER_REQVER},90 {'modname': "diff_match_patch",91 'package_name': "diff-match-patch",92 'features': _("Compute text file diff changes during edition"),93 'required_version': DIFF_MATCH_PATCH_REQVER},94 {'modname': "intervaltree",95 'package_name': "intervaltree",96 'features': _("Compute folding range nesting levels"),97 'required_version': INTERVALTREE_REQVER},98 {'modname': "IPython",99 'package_name': "IPython",100 'features': _("IPython interactive python environment"),101 'required_version': IPYTHON_REQVER},102 {'modname': "jedi",103 'package_name': "jedi",104 'features': _("Main backend for the Python Language Server"),105 'required_version': JEDI_REQVER},106 {'modname': "keyring",107 'package_name': "keyring",108 'features': _("Save Github credentials to report internal "109 "errors securely"),110 'required_version': KEYRING_REQVER,111 'display': sys.platform.startswith('linux') and not PY2},112 {'modname': "nbconvert",113 'package_name': "nbconvert",114 'features': _("Manipulate Jupyter notebooks in the Editor"),115 'required_version': NBCONVERT_REQVER},116 {'modname': "numpydoc",117 'package_name': "numpydoc",118 'features': _("Improve code completion for objects that use Numpy docstrings"),119 'required_version': NUMPYDOC_REQVER},120 {'modname': "paramiko",121 'package_name': "paramiko",122 'features': _("Connect to remote kernels through SSH"),123 'required_version': PARAMIKO_REQVER,124 'display': os.name == 'nt'},125 {'modname': "parso",126 'package_name': "parso",127 'features': _("Python parser that supports error recovery and "128 "round-trip parsing"),129 'required_version': PARSO_REQVER},130 {'modname': "pexpect",131 'package_name': "pexpect",132 'features': _("Stdio support for our language server client"),133 'required_version': PEXPECT_REQVER},134 {'modname': "pickleshare",135 'package_name': "pickleshare",136 'features': _("Cache the list of installed Python modules"),137 'required_version': PICKLESHARE_REQVER},138 {'modname': "psutil",139 'package_name': "psutil",140 'features': _("CPU and memory usage info in the status bar"),141 'required_version': PSUTIL_REQVER},142 {'modname': "pygments",143 'package_name': "pygments",144 'features': _("Syntax highlighting for a lot of file types in the Editor"),145 'required_version': PYGMENTS_REQVER},146 {'modname': "pylint",147 'package_name': "pylint",148 'features': _("Static code analysis"),149 'required_version': PYLINT_REQVER},150 {'modname': 'pyls',151 'package_name': 'python-language-server',152 'features': _("Code completion and linting for the Editor"),153 'required_version': PYLS_REQVER},154 {'modname': "xdg",155 'package_name': "pyxdg",156 'features': _("Parse desktop files on Linux"),157 'required_version': PYXDG_REQVER,158 'display': sys.platform.startswith('linux')},159 {'modname': "zmq",160 'package_name': "pyzmq",161 'features': _("Client for the language server protocol (LSP)"),162 'required_version': PYZMQ_REQVER},163 {'modname': "qdarkstyle",164 'package_name': "qdarkstyle",165 'features': _("Dark style for the entire interface"),166 'required_version': QDARKSTYLE_REQVER},167 {'modname': "qtawesome",168 'package_name': "qtawesome",169 'features': _("Icon theme based on FontAwesome and Material Design icons"),170 'required_version': QTAWESOME_REQVER},171 {'modname': "qtconsole",172 'package_name': "qtconsole",173 'features': _("Main package for the IPython console"),174 'required_version': QTCONSOLE_REQVER},175 {'modname': "qtpy",176 'package_name': "qtpy",177 'features': _("Abstraction layer for Python Qt bindings."),178 'required_version': QTPY_REQVER},179 {'modname': "rtree",180 'package_name': "rtree",181 'features': _("Fast access to code snippets regions"),182 'required_version': RTREE_REQVER,183 'display': is_anaconda()},184 {'modname': "sphinx",185 'package_name': "sphinx",186 'features': _("Show help for objects in the Editor and Consoles in a dedicated pane"),187 'required_version': SPHINX_REQVER},188 {'modname': "spyder_kernels",189 'package_name': "spyder-kernels",190 'features': _("Jupyter kernels for the Spyder console"),191 'required_version': SPYDER_KERNELS_REQVER},192 {'modname': "watchdog",193 'package_name': "watchdog",194 'features': _("Watch file changes on project directories"),195 'required_version': WATCHDOG_REQVER},196]197# Optional dependencies198DESCRIPTIONS += [199 {'modname': "cython",200 'package_name': "cython",201 'features': _("Run Cython files in the IPython Console"),202 'required_version': CYTHON_REQVER,203 'kind': OPTIONAL},204 {'modname': "matplotlib",205 'package_name': "matplotlib",206 'features': _("2D/3D plotting in the IPython console"),207 'required_version': MATPLOTLIB_REQVER,208 'kind': OPTIONAL},209 {'modname': "numpy",210 'package_name': "numpy",211 'features': _("View and edit two and three dimensional arrays in the Variable Explorer"),212 'required_version': NUMPY_REQVER,213 'kind': OPTIONAL},214 {'modname': 'pandas',215 'package_name': 'pandas',216 'features': _("View and edit DataFrames and Series in the Variable Explorer"),217 'required_version': PANDAS_REQVER,218 'kind': OPTIONAL},219 {'modname': "scipy",220 'package_name': "scipy",221 'features': _("Import Matlab workspace files in the Variable Explorer"),222 'required_version': SCIPY_REQVER,223 'kind': OPTIONAL},224 {'modname': "sympy",225 'package_name': "sympy",226 'features': _("Symbolic mathematics in the IPython Console"),227 'required_version': SYMPY_REQVER,228 'kind': OPTIONAL}229]230# =============================================================================231# Code232# =============================================================================233class Dependency(object):234 """Spyder's dependency235 version may starts with =, >=, > or < to specify the exact requirement ;236 multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0')"""237 OK = 'OK'238 NOK = 'NOK'239 def __init__(self, modname, package_name, features, required_version,240 installed_version=None, kind=MANDATORY):241 self.modname = modname242 self.package_name = package_name243 self.features = features244 self.required_version = required_version245 self.kind = kind246 if installed_version is None:247 try:248 self.installed_version = programs.get_module_version(modname)249 except Exception:250 # NOTE: Don't add any exception type here!251 # Modules can fail to import in several ways besides252 # ImportError253 self.installed_version = None254 else:255 self.installed_version = installed_version256 def check(self):257 """Check if dependency is installed"""258 if self.required_version and self.installed_version:259 return programs.is_module_installed(self.modname,260 self.required_version,261 self.installed_version)262 else:263 return True264 def get_installed_version(self):265 """Return dependency status (string)"""266 if self.check():267 return '%s (%s)' % (self.installed_version, self.OK)268 else:269 return '%s (%s)' % (self.installed_version, self.NOK)270 def get_status(self):271 """Return dependency status (string)"""272 if self.check():273 return self.OK274 else:275 return self.NOK276DEPENDENCIES = []277def add(modname, package_name, features, required_version,278 installed_version=None, kind=MANDATORY):279 """Add Spyder dependency"""280 global DEPENDENCIES281 for dependency in DEPENDENCIES:282 if dependency.modname == modname:283 raise ValueError("Dependency has already been registered: %s"\284 % modname)285 DEPENDENCIES += [Dependency(modname, package_name, features,286 required_version,287 installed_version, kind)]288def check(modname):289 """Check if required dependency is installed"""290 for dependency in DEPENDENCIES:291 if dependency.modname == modname:292 return dependency.check()293 else:294 raise RuntimeError("Unkwown dependency %s" % modname)295def status(deps=DEPENDENCIES, linesep=os.linesep):296 """Return a status of dependencies."""297 maxwidth = 0298 data = []299 # Find maximum width300 for dep in deps:301 title = dep.modname302 if dep.required_version is not None:303 title += ' ' + dep.required_version304 maxwidth = max([maxwidth, len(title)])305 dep_order = {MANDATORY: '0', OPTIONAL: '1', PLUGIN: '2'}306 order_dep = {'0': MANDATORY, '1': OPTIONAL, '2': PLUGIN}307 data.append([dep_order[dep.kind], title, dep.get_installed_version()])308 # Construct text and sort by kind and name309 maxwidth += 1310 text = ""311 prev_order = '-1'312 for order, title, version in sorted(data,313 key=lambda x: x[0] + x[1].lower()):314 if order != prev_order:315 text += '{sep}# {name}:{sep}'.format(316 sep=linesep, name=order_dep[order].capitalize())317 prev_order = order318 text += '{title}: {version}{linesep}'.format(319 title=title.ljust(maxwidth), version=version, linesep=linesep)320 # Remove spurious linesep when reporting deps to Github321 if not linesep == '<br>':322 text = text[:-1]323 return text324def missing_dependencies():325 """Return the status of missing dependencies (if any)"""326 missing_deps = []327 for dependency in DEPENDENCIES:328 if not dependency.check() and dependency.kind != OPTIONAL:329 missing_deps.append(dependency)330 if missing_deps:331 return status(deps=missing_deps, linesep='<br>')332 else:333 return ""334def declare_dependencies():335 for dep in DESCRIPTIONS:336 if dep.get('display', True):337 add(dep['modname'], dep['package_name'],338 dep['features'], dep['required_version'],...
manager.py
Source:manager.py
1'''2Created on Aug 14, 20093@author: abi.mohammadi, majid.vesal4'''5import sys6import os7import ConfigParser8from deltapy.core import DeltaException, DeltaObject9from deltapy.packaging.package import Package, PackageException10from deltapy.utils import get_module_dir, get_module_parent11import deltapy.application.services as application_services12class PackageManagerException(DeltaException):13 pass14 15class DependencyException(PackageManagerException):16 '''17 A class for handling packages dependency exceptions.18 '''19 pass20class PackageManager(DeltaObject):21 '''22 Provides some functionality for managing packages. 23 '''24 25 def __init__(self):26 DeltaObject.__init__(self)27 self.__loaded_packages__ = {}28 self.__hooks = []29 self.__disabled_packages = []30 self._read_disabled_packages_config_()31 32 def _read_disabled_packages_config_(self):33 '''34 '''35 36 try:37 setting_folder = \38 application_services.get_default_settings_folder_name()39 package_dir = \40 get_module_dir(application_services.get_name())41 settings_dir = \42 os.path.join(package_dir, setting_folder)43 44 app_setting_file_name = \45 os.path.join(settings_dir, 'app.config') 46 47 config_parser = ConfigParser.ConfigParser()48 config_parser.read(app_setting_file_name)49 50 if config_parser.has_section('packages'):51 disabled_packages = config_parser.get('packages', 52 'disabled_packages', 53 None)54 if disabled_packages is not None:55 disabled_packages_list = disabled_packages.split(',')56 for disabled_package in disabled_packages_list:57 striped_disabled_package = disabled_package.strip() 58 if striped_disabled_package != '':59 self.__disabled_packages.append(striped_disabled_package)60 except:61 import traceback62 print traceback.format_exc()63 64 def __reset_package__(self, package_name):65 related_modules = self.get_related_modules(package_name)66 for module in related_modules:67 if module.find(package_name) == 0:68 sys.modules.pop(module)69 70 def get_related_modules(self, package_name):71 '''72 Returns related modules of the package.73 74 @param package_name: package name75 '''76 77 return [module for module in sys.modules if module.find(package_name) == 0]78 79 def probe_package_class(self, parent, package_name, package_class):80 '''81 Probes the package class.82 83 @param parent: parent84 @param package_name: package name85 @param package_class: package class86 @return: boolean87 '''88 for hook in self.__hooks:89 if not hook.probe_package_class(self,90 parent,91 package_name, 92 package_class):93 return False94 return True95 96 def before_load(self, parent, package_name):97 '''98 Is called before loading package.99 100 @param parent: parent101 @param package_name: package name102 '''103 for hook in self.__hooks:104 hook.before_load(self,105 parent,106 package_name) 107 def after_load(self, 108 parent, 109 package_name, 110 package):111 '''112 Is called after loading package.113 114 @param parent: parent115 @param package_name: package name116 @param package: package instance117 '''118 for hook in self.__hooks:119 hook.after_load(self,120 parent,121 package_name,122 package) 123 def before_unload(self, package_name):124 '''125 Is called before loading package.126 127 @param parent: parent128 @param package_name: package name129 '''130 for hook in self.__hooks:131 hook.before_load(self,132 package_name) 133 def after_unload(self, package_name):134 '''135 Is called after loading package.136 137 @param parent: parent138 @param package_name: package name139 @param package: package instance140 '''141 for hook in self.__hooks:142 hook.after_unload(self,143 package_name) 144 def __get_package_class__(self, parent, package_name):145 if package_name not in self.__loaded_packages__:146 try:147 module = __import__(package_name, fromlist=parent or [])148 except ImportError:149 return None, None150 151 package_class = None152 for cls in module.__dict__.values():153 try:154 if cls is not Package and issubclass(cls, Package):155 if not getattr(cls, '__disable__') and package_name not in self.__disabled_packages:156 package_class = cls157 break158 else:159 print "Package [%s] is disable." % package_name 160 except TypeError:161 pass162 return module, package_class163 164 return None, None165 166 def __auto_import__(self, package_name, parent):167 try:168 package_dir = get_module_dir(package_name)169 sub_modules = os.listdir(package_dir)170 for module_name in sub_modules:171 if module_name.find('__init__.py') == 0:172 continue173 head, sep, tail = module_name.partition('.')174 module = __import__("%s.%s" % (package_name, head), fromlist=parent or [])175 except Exception:176 print 'Error in loading package [{0}]'.format(package_name)177 raise 178 179 def __load__(self, package_name, parent = None):180 181 # Doing before loading package actions.182 self.before_load(parent, package_name)183 184 # Getting package class185 module, package_class = self.__get_package_class__(parent, package_name)186 187 if not package_class: 188 #self.__reset_package__(package_name)189 return None190 191 if self.probe_package_class(parent, 192 package_name, 193 package_class):194 195 # Checking dependencies196 self._load_depends_(package_class, parent)197 198 # Creating instance...199 package = package_class()200 package.module = module201 package.name = module.__name__202 203 # Loading package...204 package.load()205 206 # Getting auto import modules207 auto_imports = getattr(package_class, '__auto_imports__')208 209 # Registering package...210 self.__loaded_packages__[package_name] = package211 212 package_dir = os.path.dirname(module.__file__)213 sub_dirs = os.listdir(package_dir)214 auto_imports = list(set(sub_dirs).intersection(set(auto_imports)))215 sub_packages = auto_imports + \216 list(set(sub_dirs).difference(set(auto_imports)))217 for sub_package in sub_packages:218 if sub_package.find('.') < 0:219 pkg = self.__load__("%s.%s" % (package_name, 220 sub_package), 221 [package_name])222 if sub_package in auto_imports:223 self.__auto_import__("%s.%s" % (package_name, 224 sub_package), 225 [package_name])226 227 if pkg:228 package.add_package(pkg)229 230 231 print "Package [%s] loaded." % package_name232 233 self.after_load(parent, package_name, package)234 235 return package236 237 def _load_depends_(self, package_class, parent):238 '''239 Loads all packages which this packages depends those.240 241 @param package_class: package class242 @param parent: parent243 '''244 for package_name in package_class.__depends__:245 package = self.__load__(package_name, parent)246 if not package:247 DependencyException('Loading package[%s] failed. Could not load package[%s]' % (package_class, package_name))248 249 def load(self, package_name):250 '''251 Loads the package and it's sub packages.252 253 @param package_name: package name254 '''255 256 print ">> Disabled packages:"257 for disabled_package in self.__disabled_packages:258 print " [%s]" % disabled_package 259 260 parent = []261 if get_module_parent(package_name):262 parent.append(get_module_parent(package_name)) 263 self.__load__(package_name, parent)264 path = get_module_dir(package_name)265 sub_packages = os.listdir(path)266 for sub_package in sub_packages:267 if sub_package.find('.') < 0:268 self.__load__("%s.%s" % (package_name, sub_package), [package_name])269 270 loaded_packages_count = len(self.get_loaded_packages(package_name)) 271 272 print ""273 print ">> %s:[%d] packages loaded." % (package_name, loaded_packages_count)274 print ">> Total loaded packages: %d" % (len(self.get_loaded_packages()))275 print ">> Disabled packages: %d" % (len(self.__disabled_packages))276 print ""277 278 return loaded_packages_count279 280 def get_package(self, package_name):281 '''282 Returns the package by the given name.283 284 @param package_name: package name285 '''286 return self.__loaded_packages__.get(package_name, None) 287 288 def unload(self, package_name):289 '''290 Unloads the package completely.291 292 @param package_name: package name293 '''294 295 self.before_unload(package_name)296 297 package = self.get_package(package_name)298 if package: 299 if not package.__unloadable__:300 raise PackageException("Package [%s] is unloadable." % package_name)301 print "Unloading packages from[%s]" % package 302 try:303 import deltapy.commander.services as commander304 commander.remove_commands(package_name)305 except ImportError:306 pass307 308 for sub_package in package.get_packages():309 self.unload(sub_package)310 311 package.unload()312 313 self.__reset_package__(package_name)314 315 module = self.__loaded_packages__.pop(package_name)316 317 del module318 del package319 320 self.after_unload(package_name)321 322 def reload(self, package_name):323 '''324 Reloads the package.325 326 @param package_name: package name327 '''328 package = self.get_package(package_name)329 if package:330 package_name = package.module.__name__331 self.unload(package_name)332 self.load(package_name)333 334 def get_loaded_packages(self, parent_name = None):335 '''336 Returns all loaded package in parent package domain.337 338 @param parent_name: parent package name339 @return: list<Package>340 '''341 342 packages = self.__loaded_packages__.values()343 results = []344 if not parent_name:345 results = packages346 else:347 for pkg in packages:348 if hasattr(pkg,'module') \349 and pkg.module.__name__.find(parent_name) == 0:350 results.append(pkg)351 return results352 353 def get_disabled_packages(self):354 '''355 Returns all disabled packages.356 357 @return: list<Package>358 '''359 return self.__disabled_packages360 361 def add_hook(self, hook):362 '''363 Sets the package manager hook.364 365 @param hook: hook instance366 '''367 368 self.__hooks.append(hook)369 370 def get_hooks(self):371 '''372 Returns the package manager hook.373 374 @return: PackageManagerHook375 '''376 377 return self.__hooks...
element.py
Source:element.py
1package_name = 'com.google.android.calculator'2id_0_btn = package_name + ':id/digit_0'3id_1_btn = package_name + ':id/digit_1'4id_2_btn = package_name + ':id/digit_2'5id_3_btn = package_name + ':id/digit_3'6id_4_btn = package_name + ':id/digit_4'7id_5_btn = package_name + ':id/digit_5'8id_6_btn = package_name + ':id/digit_6'9id_7_btn = package_name + ':id/digit_7'10id_8_btn = package_name + ':id/digit_8'11id_9_btn = package_name + ':id/digit_9'12id_add_btn = package_name + ':id/op_add'13id_eq_btn = package_name + ':id/eq'...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!