id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
171,452
from __future__ import annotations import os import stat def raise_on_exist_ro_file(filename: str) -> None: try: file_stat = os.stat(filename) # use stat to do exists + can write to check without race condition except OSError: return None # swallow does not exist or other errors if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it if not (file_stat.st_mode & stat.S_IWUSR): raise PermissionError(f"Permission denied: {filename!r}")
null
171,453
import asyncio import concurrent.futures import inspect import itertools import logging import os import socket import sys import time import typing as t import uuid import warnings from datetime import datetime from functools import partial from signal import SIGINT, SIGTERM, Signals, default_int_handler, signal import psutil import zmq from IPython.core.error import StdinNotImplementedError from jupyter_client.session import Session from tornado import ioloop from tornado.queues import Queue, QueueEmpty from traitlets.config.configurable import SingletonConfigurable from traitlets.traitlets import ( Any, Bool, Dict, Float, Instance, Integer, List, Set, Unicode, default, observe, ) from zmq.eventloop.zmqstream import ZMQStream from ipykernel.jsonutil import json_clean from ._version import kernel_protocol_version def _accepts_cell_id(meth): parameters = inspect.signature(meth).parameters cid_param = parameters.get("cell_id") return (cid_param and cid_param.kind == cid_param.KEYWORD_ONLY) or any( p.kind == p.VAR_KEYWORD for p in parameters.values() )
null
171,454
import errno import json import os import shutil import stat import sys import tempfile from jupyter_client.kernelspec import KernelSpecManager from traitlets import Unicode KERNEL_NAME = "python%i" % sys.version_info[0] def write_kernel_spec(path=None, overrides=None, extra_arguments=None): """Write a kernel spec directory to `path` If `path` is not specified, a temporary directory is created. If `overrides` is given, the kernelspec JSON is updated before writing. The path to the kernelspec is always returned. """ if path is None: path = os.path.join(tempfile.mkdtemp(suffix="_kernels"), KERNEL_NAME) # stage resources shutil.copytree(RESOURCES, path) # ensure path is writable mask = os.stat(path).st_mode if not mask & stat.S_IWUSR: os.chmod(path, mask | stat.S_IWUSR) # write kernel.json kernel_dict = get_kernel_dict(extra_arguments) if overrides: kernel_dict.update(overrides) with open(pjoin(path, "kernel.json"), "w") as f: json.dump(kernel_dict, f, indent=1) return path from traitlets.config import Application class KernelSpecManager(LoggingConfigurable): """A manager for kernel specs.""" kernel_spec_class = Type( KernelSpec, config=True, help="""The kernel spec class. This is configurable to allow subclassing of the KernelSpecManager for customized behavior. """, ) ensure_native_kernel = Bool( True, config=True, help="""If there is no Python kernelspec registered and the IPython kernel is available, ensure it is added to the spec list. """, ) data_dir = Unicode() def _data_dir_default(self): return jupyter_data_dir() user_kernel_dir = Unicode() def _user_kernel_dir_default(self): return pjoin(self.data_dir, "kernels") whitelist = Set( config=True, help="""Deprecated, use `KernelSpecManager.allowed_kernelspecs` """, ) allowed_kernelspecs = Set( config=True, help="""List of allowed kernel names. By default, all installed kernels are allowed. """, ) kernel_dirs = List( help="List of kernel directories to search. Later ones take priority over earlier." ) _deprecated_aliases = { "whitelist": ("allowed_kernelspecs", "7.0"), } # Method copied from # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161 def _deprecated_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_aliases[old_attr] new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( ( "{cls}.{old} is deprecated in jupyter_client " "{version}, use {cls}.{new} instead" ).format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def _kernel_dirs_default(self): dirs = jupyter_path("kernels") # At some point, we should stop adding .ipython/kernels to the path, # but the cost to keeping it is very small. try: # this should always be valid on IPython 3+ from IPython.paths import get_ipython_dir dirs.append(os.path.join(get_ipython_dir(), "kernels")) except ModuleNotFoundError: pass return dirs def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" d = {} for kernel_dir in self.kernel_dirs: kernels = _list_kernels_in(kernel_dir) for kname, spec in kernels.items(): if kname not in d: self.log.debug("Found kernel %s in %s", kname, kernel_dir) d[kname] = spec if self.ensure_native_kernel and NATIVE_KERNEL_NAME not in d: try: from ipykernel.kernelspec import RESOURCES self.log.debug( "Native kernel (%s) available from %s", NATIVE_KERNEL_NAME, RESOURCES, ) d[NATIVE_KERNEL_NAME] = RESOURCES except ImportError: self.log.warning("Native kernel (%s) is not available", NATIVE_KERNEL_NAME) if self.allowed_kernelspecs: # filter if there's an allow list d = {name: spec for name, spec in d.items() if name in self.allowed_kernelspecs} return d # TODO: Caching? def _get_kernel_spec_by_name(self, kernel_name, resource_dir): """Returns a :class:`KernelSpec` instance for a given kernel_name and resource_dir. """ kspec = None if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES, get_kernel_dict except ImportError: # It should be impossible to reach this, but let's play it safe pass else: if resource_dir == RESOURCES: kspec = self.kernel_spec_class(resource_dir=resource_dir, **get_kernel_dict()) if not kspec: kspec = self.kernel_spec_class.from_resource_dir(resource_dir) if not KPF.instance(parent=self.parent).is_provisioner_available(kspec): raise NoSuchKernel(kernel_name) return kspec def _find_spec_directory(self, kernel_name): """Find the resource directory of a named kernel spec""" for kernel_dir in [kd for kd in self.kernel_dirs if os.path.isdir(kd)]: files = os.listdir(kernel_dir) for f in files: path = pjoin(kernel_dir, f) if f.lower() == kernel_name and _is_kernel_dir(path): return path if kernel_name == NATIVE_KERNEL_NAME: try: from ipykernel.kernelspec import RESOURCES except ImportError: pass else: return RESOURCES def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ if not _is_valid_kernel_name(kernel_name): self.log.warning( f"Kernelspec name {kernel_name} is invalid: {_kernel_name_description}" ) resource_dir = self._find_spec_directory(kernel_name.lower()) if resource_dir is None: self.log.warning("Kernelspec name %s cannot be found!", kernel_name) raise NoSuchKernel(kernel_name) return self._get_kernel_spec_by_name(kernel_name, resource_dir) def get_all_specs(self): """Returns a dict mapping kernel names to kernelspecs. Returns a dict of the form:: { 'kernel_name': { 'resource_dir': '/path/to/kernel_name', 'spec': {"the spec itself": ...} }, ... } """ d = self.find_kernel_specs() res = {} for kname, resource_dir in d.items(): try: if self.__class__ is KernelSpecManager: spec = self._get_kernel_spec_by_name(kname, resource_dir) else: # avoid calling private methods in subclasses, # which may have overridden find_kernel_specs # and get_kernel_spec, but not the newer get_all_specs spec = self.get_kernel_spec(kname) res[kname] = {"resource_dir": resource_dir, "spec": spec.to_dict()} except NoSuchKernel: pass # The appropriate warning has already been logged except Exception: self.log.warning("Error loading kernelspec %r", kname, exc_info=True) return res def remove_kernel_spec(self, name): """Remove a kernel spec directory by name. Returns the path that was deleted. """ save_native = self.ensure_native_kernel try: self.ensure_native_kernel = False specs = self.find_kernel_specs() finally: self.ensure_native_kernel = save_native spec_dir = specs[name] self.log.debug("Removing %s", spec_dir) if os.path.islink(spec_dir): os.remove(spec_dir) else: shutil.rmtree(spec_dir) return spec_dir def _get_destination_dir(self, kernel_name, user=False, prefix=None): if user: return os.path.join(self.user_kernel_dir, kernel_name) elif prefix: return os.path.join(os.path.abspath(prefix), "share", "jupyter", "kernels", kernel_name) else: return os.path.join(SYSTEM_JUPYTER_PATH[0], "kernels", kernel_name) def install_kernel_spec( self, source_dir, kernel_name=None, user=False, replace=None, prefix=None ): """Install a kernel spec by copying its directory. If ``kernel_name`` is not given, the basename of ``source_dir`` will be used. If ``user`` is False, it will attempt to install into the systemwide kernel registry. If the process does not have appropriate permissions, an :exc:`OSError` will be raised. If ``prefix`` is given, the kernelspec will be installed to PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix for installation inside virtual or conda envs. """ source_dir = source_dir.rstrip("/\\") if not kernel_name: kernel_name = os.path.basename(source_dir) kernel_name = kernel_name.lower() if not _is_valid_kernel_name(kernel_name): msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}" raise ValueError(msg) if user and prefix: msg = "Can't specify both user and prefix. Please choose one or the other." raise ValueError(msg) if replace is not None: warnings.warn( "replace is ignored. Installing a kernelspec always replaces an existing " "installation", DeprecationWarning, stacklevel=2, ) destination = self._get_destination_dir(kernel_name, user=user, prefix=prefix) self.log.debug("Installing kernelspec in %s", destination) kernel_dir = os.path.dirname(destination) if kernel_dir not in self.kernel_dirs: self.log.warning( "Installing to %s, which is not in %s. The kernelspec may not be found.", kernel_dir, self.kernel_dirs, ) if os.path.isdir(destination): self.log.info("Removing existing kernelspec in %s", destination) shutil.rmtree(destination) shutil.copytree(source_dir, destination) self.log.info("Installed kernelspec %s in %s", kernel_name, destination) return destination def install_native_kernel_spec(self, user=False): """DEPRECATED: Use ipykernel.kernelspec.install""" warnings.warn( "install_native_kernel_spec is deprecated. Use ipykernel.kernelspec import install.", stacklevel=2, ) from ipykernel.kernelspec import install install(self, user=user) The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install( kernel_spec_manager=None, user=False, kernel_name=KERNEL_NAME, display_name=None, prefix=None, profile=None, env=None, )` to solve the following problem: Install the IPython kernelspec for Jupyter Parameters ---------- kernel_spec_manager : KernelSpecManager [optional] A KernelSpecManager to use for installation. If none provided, a default instance will be created. user : bool [default: False] Whether to do a user-only install, or system-wide. kernel_name : str, optional Specify a name for the kernelspec. This is needed for having multiple IPython kernels for different environments. display_name : str, optional Specify the display name for the kernelspec profile : str, optional Specify a custom profile to be loaded by the kernel. prefix : str, optional Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. env : dict, optional A dictionary of extra environment variables for the kernel. These will be added to the current environment variables before the kernel is started Returns ------- The path where the kernelspec was installed. Here is the function: def install( kernel_spec_manager=None, user=False, kernel_name=KERNEL_NAME, display_name=None, prefix=None, profile=None, env=None, ): """Install the IPython kernelspec for Jupyter Parameters ---------- kernel_spec_manager : KernelSpecManager [optional] A KernelSpecManager to use for installation. If none provided, a default instance will be created. user : bool [default: False] Whether to do a user-only install, or system-wide. kernel_name : str, optional Specify a name for the kernelspec. This is needed for having multiple IPython kernels for different environments. display_name : str, optional Specify the display name for the kernelspec profile : str, optional Specify a custom profile to be loaded by the kernel. prefix : str, optional Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. env : dict, optional A dictionary of extra environment variables for the kernel. These will be added to the current environment variables before the kernel is started Returns ------- The path where the kernelspec was installed. """ if kernel_spec_manager is None: kernel_spec_manager = KernelSpecManager() if (kernel_name != KERNEL_NAME) and (display_name is None): # kernel_name is specified and display_name is not # default display_name to kernel_name display_name = kernel_name overrides = {} if display_name: overrides["display_name"] = display_name if profile: extra_arguments = ["--profile", profile] if not display_name: # add the profile to the default display name overrides["display_name"] = "Python %i [profile=%s]" % (sys.version_info[0], profile) else: extra_arguments = None if env: overrides["env"] = env path = write_kernel_spec(overrides=overrides, extra_arguments=extra_arguments) dest = kernel_spec_manager.install_kernel_spec( path, kernel_name=kernel_name, user=user, prefix=prefix ) # cleanup afterward shutil.rmtree(path) return dest
Install the IPython kernelspec for Jupyter Parameters ---------- kernel_spec_manager : KernelSpecManager [optional] A KernelSpecManager to use for installation. If none provided, a default instance will be created. user : bool [default: False] Whether to do a user-only install, or system-wide. kernel_name : str, optional Specify a name for the kernelspec. This is needed for having multiple IPython kernels for different environments. display_name : str, optional Specify the display name for the kernelspec profile : str, optional Specify a custom profile to be loaded by the kernel. prefix : str, optional Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. env : dict, optional A dictionary of extra environment variables for the kernel. These will be added to the current environment variables before the kernel is started Returns ------- The path where the kernelspec was installed.
171,455
import json import sys from subprocess import PIPE, Popen from typing import Any, Dict import jupyter_client from jupyter_client import write_connection_file def _find_connection_file(connection_file): """Return the absolute path for a connection file - If nothing specified, return current Kernel's connection file - Otherwise, call jupyter_client.find_connection_file """ if connection_file is None: # get connection file from current kernel return get_connection_file() else: return jupyter_client.find_connection_file(connection_file) The provided code snippet includes necessary dependencies for implementing the `get_connection_info` function. Write a Python function `def get_connection_info(connection_file=None, unpack=False)` to solve the following problem: Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. Here is the function: def get_connection_info(connection_file=None, unpack=False): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. """ cf = _find_connection_file(connection_file) with open(cf) as f: info_str = f.read() if unpack: info = json.loads(info_str) # ensure key is bytes: info["key"] = info.get("key", "").encode() return info return info_str
Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`.
171,456
import json import sys from subprocess import PIPE, Popen from typing import Any, Dict import jupyter_client from jupyter_client import write_connection_file def _find_connection_file(connection_file): """Return the absolute path for a connection file - If nothing specified, return current Kernel's connection file - Otherwise, call jupyter_client.find_connection_file """ if connection_file is None: # get connection file from current kernel return get_connection_file() else: return jupyter_client.find_connection_file(connection_file) PIPE: int class Popen(Generic[AnyStr]): args: _CMD stdin: Optional[IO[AnyStr]] stdout: Optional[IO[AnyStr]] stderr: Optional[IO[AnyStr]] pid: int returncode: int universal_newlines: bool # Technically it is wrong that Popen provides __new__ instead of __init__ # but this shouldn't come up hopefully? if sys.version_info >= (3, 7): # text is added in 3.7 def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: str, errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: str, ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., # where the *real* keyword only args start text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Literal[True], encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Literal[None, False] = ..., encoding: None = ..., errors: None = ..., ) -> Popen[bytes]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, text: Optional[bool] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[Any]: ... else: def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: str, errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: Optional[str] = ..., errors: str, ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., *, universal_newlines: Literal[True], startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., # where the *real* keyword only args start encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[str]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: Literal[False] = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: None = ..., errors: None = ..., ) -> Popen[bytes]: ... def __new__( cls, args: _CMD, bufsize: int = ..., executable: Optional[AnyPath] = ..., stdin: Optional[_FILE] = ..., stdout: Optional[_FILE] = ..., stderr: Optional[_FILE] = ..., preexec_fn: Optional[Callable[[], Any]] = ..., close_fds: bool = ..., shell: bool = ..., cwd: Optional[AnyPath] = ..., env: Optional[_ENV] = ..., universal_newlines: bool = ..., startupinfo: Optional[Any] = ..., creationflags: int = ..., restore_signals: bool = ..., start_new_session: bool = ..., pass_fds: Any = ..., *, encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Popen[Any]: ... def poll(self) -> Optional[int]: ... if sys.version_info >= (3, 7): def wait(self, timeout: Optional[float] = ...) -> int: ... else: def wait(self, timeout: Optional[float] = ..., endtime: Optional[float] = ...) -> int: ... # Return str/bytes def communicate( self, input: Optional[AnyStr] = ..., timeout: Optional[float] = ..., # morally this should be optional ) -> Tuple[AnyStr, AnyStr]: ... def send_signal(self, sig: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... def __enter__(self: _S) -> _S: ... def __exit__( self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... Any = object() Dict = _Alias() The provided code snippet includes necessary dependencies for implementing the `connect_qtconsole` function. Write a Python function `def connect_qtconsole(connection_file=None, argv=None)` to solve the following problem: Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. Returns ------- :class:`subprocess.Popen` instance running the qtconsole frontend Here is the function: def connect_qtconsole(connection_file=None, argv=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. Returns ------- :class:`subprocess.Popen` instance running the qtconsole frontend """ argv = [] if argv is None else argv cf = _find_connection_file(connection_file) cmd = ";".join(["from qtconsole import qtconsoleapp", "qtconsoleapp.main()"]) kwargs: Dict[str, Any] = {} # Launch the Qt console in a separate session & process group, so # interrupting the kernel doesn't kill it. kwargs["start_new_session"] = True return Popen( [sys.executable, "-c", cmd, "--existing", cf, *argv], stdout=PIPE, stderr=PIPE, close_fds=(sys.platform != "win32"), **kwargs, )
Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. Returns ------- :class:`subprocess.Popen` instance running the qtconsole frontend
171,457
import os import sys import tempfile from IPython.core.compilerop import CachingCompiler def _convert_to_long_pathname(filename): buf = ctypes.create_unicode_buffer(MAX_PATH) rv = _GetLongPathName(filename, buf, MAX_PATH) if rv != 0 and rv <= MAX_PATH: filename = buf.value return filename
null
171,458
import os import sys import tempfile from IPython.core.compilerop import CachingCompiler def murmur2_x86(data, seed): """Get the murmur2 hash.""" m = 0x5BD1E995 data = [chr(d) for d in str.encode(data, "utf8")] length = len(data) h = seed ^ length rounded_end = length & 0xFFFFFFFC for i in range(0, rounded_end, 4): k = ( (ord(data[i]) & 0xFF) | ((ord(data[i + 1]) & 0xFF) << 8) | ((ord(data[i + 2]) & 0xFF) << 16) | (ord(data[i + 3]) << 24) ) k = (k * m) & 0xFFFFFFFF k ^= k >> 24 k = (k * m) & 0xFFFFFFFF h = (h * m) & 0xFFFFFFFF h ^= k val = length & 0x03 k = 0 if val == 3: k = (ord(data[rounded_end + 2]) & 0xFF) << 16 if val in [2, 3]: k |= (ord(data[rounded_end + 1]) & 0xFF) << 8 if val in [1, 2, 3]: k |= ord(data[rounded_end]) & 0xFF h ^= k h = (h * m) & 0xFFFFFFFF h ^= h >> 13 h = (h * m) & 0xFFFFFFFF h ^= h >> 15 return h def get_tmp_directory(): """Get a temp directory.""" tmp_dir = convert_to_long_pathname(tempfile.gettempdir()) pid = os.getpid() return tmp_dir + os.sep + "ipykernel_" + str(pid) def get_tmp_hash_seed(): """Get a temp hash seed.""" hash_seed = 0xC70F6907 return hash_seed The provided code snippet includes necessary dependencies for implementing the `get_file_name` function. Write a Python function `def get_file_name(code)` to solve the following problem: Get a file name. Here is the function: def get_file_name(code): """Get a file name.""" cell_name = os.environ.get("IPYKERNEL_CELL_NAME") if cell_name is None: name = murmur2_x86(code, get_tmp_hash_seed()) cell_name = get_tmp_directory() + os.sep + str(name) + ".py" return cell_name
Get a file name.
171,459
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application The provided code snippet includes necessary dependencies for implementing the `_use_appnope` function. Write a Python function `def _use_appnope()` to solve the following problem: Should we use appnope for dealing with OS X app nap? Checks if we are on OS X 10.9 or greater. Here is the function: def _use_appnope(): """Should we use appnope for dealing with OS X app nap? Checks if we are on OS X 10.9 or greater. """ return sys.platform == "darwin" and V(platform.mac_ver()[0]) >= V("10.9")
Should we use appnope for dealing with OS X app nap? Checks if we are on OS X 10.9 or greater.
171,460
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application loop_map = { "inline": None, "nbagg": None, "webagg": None, "notebook": None, "ipympl": None, "widget": None, None: None, } The provided code snippet includes necessary dependencies for implementing the `register_integration` function. Write a Python function `def register_integration(*toolkitnames)` to solve the following problem: Decorator to register an event loop to integrate with the IPython kernel The decorator takes names to register the event loop as for the %gui magic. You can provide alternative names for the same toolkit. The decorated function should take a single argument, the IPython kernel instance, arrange for the event loop to call ``kernel.do_one_iteration()`` at least every ``kernel._poll_interval`` seconds, and start the event loop. :mod:`ipykernel.eventloops` provides and registers such functions for a few common event loops. Here is the function: def register_integration(*toolkitnames): """Decorator to register an event loop to integrate with the IPython kernel The decorator takes names to register the event loop as for the %gui magic. You can provide alternative names for the same toolkit. The decorated function should take a single argument, the IPython kernel instance, arrange for the event loop to call ``kernel.do_one_iteration()`` at least every ``kernel._poll_interval`` seconds, and start the event loop. :mod:`ipykernel.eventloops` provides and registers such functions for a few common event loops. """ def decorator(func): """Integration registration decorator.""" for name in toolkitnames: loop_map[name] = func func.exit_hook = lambda kernel: None def exit_decorator(exit_func): """@func.exit is now a decorator to register a function to be called on exit """ func.exit_hook = exit_func return exit_func func.exit = exit_decorator return func return decorator
Decorator to register an event loop to integrate with the IPython kernel The decorator takes names to register the event loop as for the %gui magic. You can provide alternative names for the same toolkit. The decorated function should take a single argument, the IPython kernel instance, arrange for the event loop to call ``kernel.do_one_iteration()`` at least every ``kernel._poll_interval`` seconds, and start the event loop. :mod:`ipykernel.eventloops` provides and registers such functions for a few common event loops.
171,461
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def _notify_stream_qt(kernel): import operator from functools import lru_cache from IPython.external.qt_for_kernel import QtCore try: from IPython.external.qt_for_kernel import enum_helper except ImportError: def enum_helper(name): return operator.attrgetter(name.rpartition(".")[0])(sys.modules[QtCore.__package__]) def process_stream_events(): """fall back to main loop when there's a socket event""" # call flush to ensure that the stream doesn't lose events # due to our consuming of the edge-triggered FD # flush returns the number of events consumed. # if there were any, wake it up if kernel.shell_stream.flush(limit=1): kernel._qt_notifier.setEnabled(False) kernel.app.qt_event_loop.quit() if not hasattr(kernel, "_qt_notifier"): fd = kernel.shell_stream.getsockopt(zmq.FD) kernel._qt_notifier = QtCore.QSocketNotifier( fd, enum_helper('QtCore.QSocketNotifier.Type').Read, kernel.app.qt_event_loop ) kernel._qt_notifier.activated.connect(process_stream_events) else: kernel._qt_notifier.setEnabled(True) # there may already be unprocessed events waiting. # these events will not wake zmq's edge-triggered FD # since edge-triggered notification only occurs on new i/o activity. # process all the waiting events immediately # so we start in a clean state ensuring that any new i/o events will notify. # schedule first call on the eventloop as soon as it's running, # so we don't block here processing events if not hasattr(kernel, "_qt_timer"): kernel._qt_timer = QtCore.QTimer(kernel.app) kernel._qt_timer.setSingleShot(True) kernel._qt_timer.timeout.connect(process_stream_events) kernel._qt_timer.start(0) The provided code snippet includes necessary dependencies for implementing the `loop_qt` function. Write a Python function `def loop_qt(kernel)` to solve the following problem: Event loop for all supported versions of Qt. Here is the function: def loop_qt(kernel): """Event loop for all supported versions of Qt.""" _notify_stream_qt(kernel) # install hook to stop event loop. # Start the event loop. kernel.app._in_event_loop = True # `exec` blocks until there's ZMQ activity. el = kernel.app.qt_event_loop # for brevity el.exec() if hasattr(el, 'exec') else el.exec_() kernel.app._in_event_loop = False
Event loop for all supported versions of Qt.
171,462
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def loop_qt_exit(kernel): kernel.app.exit()
null
171,463
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def _loop_wx(app): """Inner-loop for running the Wx eventloop Pulled from guisupport.start_event_loop in IPython < 5.2, since IPython 5.2 only checks `get_ipython().active_eventloop` is defined, rather than if the eventloop is actually running. """ app._in_event_loop = True app.MainLoop() app._in_event_loop = False The provided code snippet includes necessary dependencies for implementing the `loop_wx` function. Write a Python function `def loop_wx(kernel)` to solve the following problem: Start a kernel with wx event loop support. Here is the function: def loop_wx(kernel): """Start a kernel with wx event loop support.""" import wx # Wx uses milliseconds poll_interval = int(1000 * kernel._poll_interval) def wake(): """wake from wx""" if kernel.shell_stream.flush(limit=1): kernel.app.ExitMainLoop() return # We have to put the wx.Timer in a wx.Frame for it to fire properly. # We make the Frame hidden when we create it in the main app below. class TimerFrame(wx.Frame): def __init__(self, func): wx.Frame.__init__(self, None, -1) self.timer = wx.Timer(self) # Units for the timer are in milliseconds self.timer.Start(poll_interval) self.Bind(wx.EVT_TIMER, self.on_timer) self.func = func def on_timer(self, event): self.func() # We need a custom wx.App to create our Frame subclass that has the # wx.Timer to defer back to the tornado event loop. class IPWxApp(wx.App): def OnInit(self): self.frame = TimerFrame(wake) self.frame.Show(False) return True # The redirect=False here makes sure that wx doesn't replace # sys.stdout/stderr with its own classes. if not (getattr(kernel, "app", None) and isinstance(kernel.app, wx.App)): kernel.app = IPWxApp(redirect=False) # The import of wx on Linux sets the handler for signal.SIGINT # to 0. This is a bug in wx or gtk. We fix by just setting it # back to the Python default. import signal if not callable(signal.getsignal(signal.SIGINT)): signal.signal(signal.SIGINT, signal.default_int_handler) _loop_wx(kernel.app)
Start a kernel with wx event loop support.
171,464
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application The provided code snippet includes necessary dependencies for implementing the `loop_wx_exit` function. Write a Python function `def loop_wx_exit(kernel)` to solve the following problem: Exit the wx loop. Here is the function: def loop_wx_exit(kernel): """Exit the wx loop.""" import wx wx.Exit()
Exit the wx loop.
171,465
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... def mainloop(duration=1): """run the Cocoa eventloop for the specified duration (seconds)""" _triggered.clear() NSApp = _NSApp() _stop_after(duration) msg(NSApp, n("run")) if not _triggered.is_set(): # app closed without firing callback, # probably due to last window being closed. # Run the loop manually in this case, # since there may be events still to process (ipython/ipython#9734) CoreFoundation.CFRunLoopRun() The provided code snippet includes necessary dependencies for implementing the `loop_tk` function. Write a Python function `def loop_tk(kernel)` to solve the following problem: Start a kernel with the Tk event loop. Here is the function: def loop_tk(kernel): """Start a kernel with the Tk event loop.""" from tkinter import READABLE, Tk app = Tk() # Capability detection: # per https://docs.python.org/3/library/tkinter.html#file-handlers # file handlers are not available on Windows if hasattr(app, "createfilehandler"): # A basic wrapper for structural similarity with the Windows version class BasicAppWrapper: def __init__(self, app): self.app = app self.app.withdraw() def process_stream_events(stream, *a, **kw): """fall back to main loop when there's a socket event""" if stream.flush(limit=1): app.tk.deletefilehandler(stream.getsockopt(zmq.FD)) app.quit() app.destroy() del kernel.app_wrapper # For Tkinter, we create a Tk object and call its withdraw method. kernel.app_wrapper = BasicAppWrapper(app) notifier = partial(process_stream_events, kernel.shell_stream) # seems to be needed for tk notifier.__name__ = "notifier" # type:ignore[attr-defined] app.tk.createfilehandler(kernel.shell_stream.getsockopt(zmq.FD), READABLE, notifier) # schedule initial call after start app.after(0, notifier) app.mainloop() else: import asyncio import nest_asyncio nest_asyncio.apply() doi = kernel.do_one_iteration # Tk uses milliseconds poll_interval = int(1000 * kernel._poll_interval) class TimedAppWrapper: def __init__(self, app, func): self.app = app self.app.withdraw() self.func = func def on_timer(self): loop = asyncio.get_event_loop() try: loop.run_until_complete(self.func()) except Exception: kernel.log.exception("Error in message handler") self.app.after(poll_interval, self.on_timer) def start(self): self.on_timer() # Call it once to get things going. self.app.mainloop() kernel.app_wrapper = TimedAppWrapper(app, doi) kernel.app_wrapper.start()
Start a kernel with the Tk event loop.
171,466
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application The provided code snippet includes necessary dependencies for implementing the `loop_tk_exit` function. Write a Python function `def loop_tk_exit(kernel)` to solve the following problem: Exit the tk loop. Here is the function: def loop_tk_exit(kernel): """Exit the tk loop.""" try: kernel.app_wrapper.app.destroy() del kernel.app_wrapper except (RuntimeError, AttributeError): pass
Exit the tk loop.
171,467
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application class GTKEmbed: """A class to embed a kernel into the GTK main event loop.""" def __init__(self, kernel): """Initialize the embed.""" self.kernel = kernel # These two will later store the real gtk functions when we hijack them self.gtk_main = None self.gtk_main_quit = None def start(self): """Starts the GTK main event loop and sets our kernel startup routine.""" # Register our function to initiate the kernel and start gtk gobject.idle_add(self._wire_kernel) gtk.main() def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel) return False def iterate_kernel(self): """Run one iteration of the kernel and return True. GTK timer functions must return True to be called again, so we make the call to :meth:`do_one_iteration` and then return True for GTK. """ self.kernel.do_one_iteration() return True def stop(self): """Stop the embed.""" # FIXME: this one isn't getting called because we have no reliable # kernel shutdown. We need to fix that: once the kernel has a # shutdown mechanism, it can call this. if self.gtk_main_quit: self.gtk_main_quit() sys.exit() def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit """ def dummy(*args, **kw): """No-op.""" pass # save and trap main and main_quit from gtk orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit class GTKEmbed: """A class to embed a kernel into the GTK main event loop.""" def __init__(self, kernel): """Initialize the embed.""" self.kernel = kernel # These two will later store the real gtk functions when we hijack them self.gtk_main = None self.gtk_main_quit = None def start(self): """Starts the GTK main event loop and sets our kernel startup routine.""" # Register our function to initiate the kernel and start gtk GObject.idle_add(self._wire_kernel) Gtk.main() def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() GObject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel) return False def iterate_kernel(self): """Run one iteration of the kernel and return True. GTK timer functions must return True to be called again, so we make the call to :meth:`do_one_iteration` and then return True for GTK. """ self.kernel.do_one_iteration() return True def stop(self): """Stop the embed.""" # FIXME: this one isn't getting called because we have no reliable # kernel shutdown. We need to fix that: once the kernel has a # shutdown mechanism, it can call this. if self.gtk_main_quit: self.gtk_main_quit() sys.exit() def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - Gtk.main - Gtk.main_quit """ def dummy(*args, **kw): """No-op.""" pass # save and trap main and main_quit from gtk orig_main, Gtk.main = Gtk.main, dummy orig_main_quit, Gtk.main_quit = Gtk.main_quit, dummy return orig_main, orig_main_quit The provided code snippet includes necessary dependencies for implementing the `loop_gtk` function. Write a Python function `def loop_gtk(kernel)` to solve the following problem: Start the kernel, coordinating with the GTK event loop Here is the function: def loop_gtk(kernel): """Start the kernel, coordinating with the GTK event loop""" from .gui.gtkembed import GTKEmbed gtk_kernel = GTKEmbed(kernel) gtk_kernel.start() kernel._gtk = gtk_kernel
Start the kernel, coordinating with the GTK event loop
171,468
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) The provided code snippet includes necessary dependencies for implementing the `loop_gtk_exit` function. Write a Python function `def loop_gtk_exit(kernel)` to solve the following problem: Exit the gtk loop. Here is the function: def loop_gtk_exit(kernel): """Exit the gtk loop.""" kernel._gtk.stop()
Exit the gtk loop.
171,469
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application class GTKEmbed: """A class to embed a kernel into the GTK main event loop.""" def __init__(self, kernel): """Initialize the embed.""" self.kernel = kernel # These two will later store the real gtk functions when we hijack them self.gtk_main = None self.gtk_main_quit = None def start(self): """Starts the GTK main event loop and sets our kernel startup routine.""" # Register our function to initiate the kernel and start gtk gobject.idle_add(self._wire_kernel) gtk.main() def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel) return False def iterate_kernel(self): """Run one iteration of the kernel and return True. GTK timer functions must return True to be called again, so we make the call to :meth:`do_one_iteration` and then return True for GTK. """ self.kernel.do_one_iteration() return True def stop(self): """Stop the embed.""" # FIXME: this one isn't getting called because we have no reliable # kernel shutdown. We need to fix that: once the kernel has a # shutdown mechanism, it can call this. if self.gtk_main_quit: self.gtk_main_quit() sys.exit() def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit """ def dummy(*args, **kw): """No-op.""" pass # save and trap main and main_quit from gtk orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit class GTKEmbed: """A class to embed a kernel into the GTK main event loop.""" def __init__(self, kernel): """Initialize the embed.""" self.kernel = kernel # These two will later store the real gtk functions when we hijack them self.gtk_main = None self.gtk_main_quit = None def start(self): """Starts the GTK main event loop and sets our kernel startup routine.""" # Register our function to initiate the kernel and start gtk GObject.idle_add(self._wire_kernel) Gtk.main() def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() GObject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel) return False def iterate_kernel(self): """Run one iteration of the kernel and return True. GTK timer functions must return True to be called again, so we make the call to :meth:`do_one_iteration` and then return True for GTK. """ self.kernel.do_one_iteration() return True def stop(self): """Stop the embed.""" # FIXME: this one isn't getting called because we have no reliable # kernel shutdown. We need to fix that: once the kernel has a # shutdown mechanism, it can call this. if self.gtk_main_quit: self.gtk_main_quit() sys.exit() def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - Gtk.main - Gtk.main_quit """ def dummy(*args, **kw): """No-op.""" pass # save and trap main and main_quit from gtk orig_main, Gtk.main = Gtk.main, dummy orig_main_quit, Gtk.main_quit = Gtk.main_quit, dummy return orig_main, orig_main_quit The provided code snippet includes necessary dependencies for implementing the `loop_gtk3` function. Write a Python function `def loop_gtk3(kernel)` to solve the following problem: Start the kernel, coordinating with the GTK event loop Here is the function: def loop_gtk3(kernel): """Start the kernel, coordinating with the GTK event loop""" from .gui.gtk3embed import GTKEmbed gtk_kernel = GTKEmbed(kernel) gtk_kernel.start() kernel._gtk = gtk_kernel
Start the kernel, coordinating with the GTK event loop
171,470
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) The provided code snippet includes necessary dependencies for implementing the `loop_gtk3_exit` function. Write a Python function `def loop_gtk3_exit(kernel)` to solve the following problem: Exit the gtk3 loop. Here is the function: def loop_gtk3_exit(kernel): """Exit the gtk3 loop.""" kernel._gtk.stop()
Exit the gtk3 loop.
171,471
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) def mainloop(duration=1): """run the Cocoa eventloop for the specified duration (seconds)""" _triggered.clear() NSApp = _NSApp() _stop_after(duration) msg(NSApp, n("run")) if not _triggered.is_set(): # app closed without firing callback, # probably due to last window being closed. # Run the loop manually in this case, # since there may be events still to process (ipython/ipython#9734) CoreFoundation.CFRunLoopRun() The provided code snippet includes necessary dependencies for implementing the `loop_cocoa` function. Write a Python function `def loop_cocoa(kernel)` to solve the following problem: Start the kernel, coordinating with the Cocoa CFRunLoop event loop via the matplotlib MacOSX backend. Here is the function: def loop_cocoa(kernel): """Start the kernel, coordinating with the Cocoa CFRunLoop event loop via the matplotlib MacOSX backend. """ from ._eventloop_macos import mainloop, stop real_excepthook = sys.excepthook def handle_int(etype, value, tb): """don't let KeyboardInterrupts look like crashes""" # wake the eventloop when we get a signal stop() if etype is KeyboardInterrupt: print("KeyboardInterrupt caught in CFRunLoop", file=sys.__stdout__) else: real_excepthook(etype, value, tb) while not kernel.shell.exit_now: try: # double nested try/except, to properly catch KeyboardInterrupt # due to pyzmq Issue #130 try: # don't let interrupts during mainloop invoke crash_handler: sys.excepthook = handle_int mainloop(kernel._poll_interval) if kernel.shell_stream.flush(limit=1): # events to process, return control to kernel return except BaseException: raise except KeyboardInterrupt: # Ctrl-C shouldn't crash the kernel print("KeyboardInterrupt caught in kernel", file=sys.__stdout__) finally: # ensure excepthook is restored sys.excepthook = real_excepthook
Start the kernel, coordinating with the Cocoa CFRunLoop event loop via the matplotlib MacOSX backend.
171,472
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) The provided code snippet includes necessary dependencies for implementing the `loop_cocoa_exit` function. Write a Python function `def loop_cocoa_exit(kernel)` to solve the following problem: Exit the cocoa loop. Here is the function: def loop_cocoa_exit(kernel): """Exit the cocoa loop.""" from ._eventloop_macos import stop stop()
Exit the cocoa loop.
171,473
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) The provided code snippet includes necessary dependencies for implementing the `loop_asyncio` function. Write a Python function `def loop_asyncio(kernel)` to solve the following problem: Start a kernel with asyncio event loop support. Here is the function: def loop_asyncio(kernel): """Start a kernel with asyncio event loop support.""" import asyncio loop = asyncio.get_event_loop() # loop is already running (e.g. tornado 5), nothing left to do if loop.is_running(): return if loop.is_closed(): # main loop is closed, create a new one loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop._should_close = False # type:ignore[attr-defined] # pause eventloop when there's an event on a zmq socket def process_stream_events(stream): """fall back to main loop when there's a socket event""" if stream.flush(limit=1): loop.stop() notifier = partial(process_stream_events, kernel.shell_stream) loop.add_reader(kernel.shell_stream.getsockopt(zmq.FD), notifier) loop.call_soon(notifier) while True: error = None try: loop.run_forever() except KeyboardInterrupt: continue except Exception as e: error = e if loop._should_close: # type:ignore[attr-defined] loop.close() if error is not None: raise error break
Start a kernel with asyncio event loop support.
171,474
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application def stop(timer=None, loop=None): """Callback to fire when there's input to be read""" _triggered.set() NSApp = _NSApp() # if NSApp is not running, stop CFRunLoop directly, # otherwise stop and wake NSApp if msg(NSApp, n("isRunning")): msg(NSApp, n("stop:"), NSApp) _wake(NSApp) else: CFRunLoopStop(CFRunLoopGetCurrent()) The provided code snippet includes necessary dependencies for implementing the `loop_asyncio_exit` function. Write a Python function `def loop_asyncio_exit(kernel)` to solve the following problem: Exit hook for asyncio Here is the function: def loop_asyncio_exit(kernel): """Exit hook for asyncio""" import asyncio loop = asyncio.get_event_loop() @asyncio.coroutine def close_loop(): if hasattr(loop, "shutdown_asyncgens"): yield from loop.shutdown_asyncgens() loop._should_close = True # type:ignore[attr-defined] loop.stop() if loop.is_running(): close_loop() elif not loop.is_closed(): loop.run_until_complete(close_loop) # type:ignore[call-overload] loop.close()
Exit hook for asyncio
171,475
import os import platform import sys from functools import partial import zmq from packaging.version import Version as V from traitlets.config.application import Application loop_map = { "inline": None, "nbagg": None, "webagg": None, "notebook": None, "ipympl": None, "widget": None, None: None, } def make_qt_app_for_kernel(gui, kernel): """Sets the `QT_API` environment variable if it isn't already set.""" if hasattr(kernel, 'app'): # Kernel is already running a Qt event loop, so there's no need to # create another app for it. return set_qt_api_env_from_gui(gui) # This import is guaranteed to work now: from IPython.external.qt_for_kernel import QtCore, QtGui from IPython.lib.guisupport import get_app_qt4 kernel.app = get_app_qt4([" "]) if isinstance(kernel.app, QtGui.QApplication): kernel.app.setQuitOnLastWindowClosed(False) kernel.app.qt_event_loop = QtCore.QEventLoop(kernel.app) class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name: t.Union[str, Unicode] = Unicode("application") # The description of the application that is printed at the beginning # of the help. description: t.Union[str, Unicode] = Unicode("This is an application.") # default section descriptions option_description: t.Union[str, Unicode] = Unicode(option_description) keyvalue_description: t.Union[str, Unicode] = Unicode(keyvalue_description) subcommand_description: t.Union[str, Unicode] = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples: t.Union[str, Unicode] = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes: t.List[t.Type[t.Any]] = [] def _classes_inc_parents(self, classes=None): """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version: t.Union[str, Unicode] = Unicode("0.0") # the argv used to initialize the application argv: t.Union[t.List[str], List] = List() # Whether failing to load config files should prevent startup raise_config_file_errors: t.Union[bool, Bool] = Bool( TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR ) # The log level for the application log_level: t.Union[str, int, Enum] = Enum( (0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"), default_value=logging.WARN, help="Set the log level by value or name.", ).tag(config=True) _log_formatter_cls = LevelFormatter log_datefmt: t.Union[str, Unicode] = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s" ).tag(config=True) log_format: t.Union[str, Unicode] = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) def get_default_logging_config(self): """Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. """ config: t.Dict[str, t.Any] = { "version": 1, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console", "level": logging.getLevelName(self.log_level), "stream": "ext://sys.stderr", }, }, "formatters": { "console": { "class": ( f"{self._log_formatter_cls.__module__}" f".{self._log_formatter_cls.__name__}" ), "format": self.log_format, "datefmt": self.log_datefmt, }, }, "loggers": { self.__class__.__name__: { "level": "DEBUG", "handlers": ["console"], } }, "disable_existing_loggers": False, } if IS_PYTHONW: # disable logging # (this should really go to a file, but file-logging is only # hooked up in parallel applications) del config["handlers"] del config["loggers"] return config def _observe_logging_change(self, change): # convert log level strings to ints log_level = self.log_level if isinstance(log_level, str): self.log_level = getattr(logging, log_level) self._configure_logging() def _observe_logging_default(self, change): self._configure_logging() def _configure_logging(self): config = self.get_default_logging_config() nested_update(config, self.logging_config or {}) dictConfig(config) # make a note that we have configured logging self._logging_configured = True def _log_default(self): """Start logging for this application.""" log = logging.getLogger(self.__class__.__name__) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent # type:ignore[assignment] return log logging_config = Dict( help=""" Configure additional log handlers. The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings. This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers. If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema This dictionary is merged with the base logging configuration which defines the following: * A logging formatter intended for interactive use called ``console``. * A logging handler that writes to stderr called ``console`` which uses the formatter ``console``. * A logger with the name of this application set to ``DEBUG`` level. This example adds a new handler that writes to a file: .. code-block:: python c.Application.logging_config = { 'handlers': { 'file': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'filename': '<path/to/file>', } }, 'loggers': { '<application-name>': { 'level': 'DEBUG', # NOTE: if you don't list the default "console" # handler here then it will be disabled 'handlers': ['console', 'file'], }, } } """, ).tag(config=True) #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text), # or just the "Class.trait" string, in which case the help text is inferred from the # corresponding trait aliases: t.Dict[t.Union[str, t.Tuple[str, ...]], t.Union[str, t.Tuple[str, str]]] = { "log-level": "Application.log_level" } # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags: t.Dict[ t.Union[str, t.Tuple[str, ...]], t.Tuple[t.Union[t.Dict[str, t.Any], Config], str] ] = { "debug": ( { "Application": { "log_level": logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging.", ), "show-config": ( { "Application": { "show_config": True, }, }, "Show the application's configuration (human-readable format)", ), "show-config-json": ( { "Application": { "show_config_json": True, }, }, "Show the application's configuration (json format)", ), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands: t.Union[t.Dict[str, t.Tuple[t.Any, str]], Dict] = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance("traitlets.config.application.Application", allow_none=True) # extra command-line arguments that don't set config values extra_args: t.Union[t.List[str], List] = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """, ) _loaded_config_files = List() show_config: t.Union[bool, Bool] = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json: t.Union[bool, Bool] = Bool( help="Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) def _show_config_json_changed(self, change): self.show_config = change.new def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config # type:ignore[assignment] def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls] + self.classes else: self.classes.insert(0, self.__class__) def _config_changed(self, change): super()._config_changed(change) self.log.debug("Config changed: %r", change.new) def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def start_show_config(self): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop("show_config", None) cls_config.pop("show_config_json", None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write("\n") return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(" " + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs: t.Dict[str, t.Any] = dict(indent=4, compact=True) for traitname in sorted(class_config): value = class_config[traitname] print( " .{} = {}".format( traitname, pprint.pformat(value, **pformat_kwargs), ) ) def print_alias_help(self): """Print the alias parts of the help.""" print("\n".join(self.emit_alias_help())) def emit_alias_help(self): """Yield the lines for alias part of the help.""" if not self.aliases: return classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c fhelp: t.Optional[str] for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split(".")[-2:] longname = classname + "." + traitname cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): alias = (alias,) alias = sorted(alias, key=len) # type:ignore[assignment] alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias) # reformat first line assert fhelp is not None fhelp[0] = fhelp[0].replace("--" + longname, alias) # type:ignore yield from fhelp yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex) raise def print_flag_help(self): """Print the flag part of the help.""" print("\n".join(self.emit_flag_help())) def emit_flag_help(self): """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): flags = (flags,) flags = sorted(flags, key=len) # type:ignore[assignment] flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = " ".join( f"--{clname}.{prop}={val}" for clname, props_dict in cfg.items() for prop, val in props_dict.items() ) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex) raise def print_options(self): """Print the options part of the help.""" print("\n".join(self.emit_options_help())) def emit_options_help(self): """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = "Options" yield header yield "=" * len(header) for p in wrap_paragraphs(self.option_description): yield p yield "" yield from self.emit_flag_help() yield from self.emit_alias_help() yield "" def print_subcommands(self): """Print the subcommand part of the help.""" print("\n".join(self.emit_subcommands_help())) def emit_subcommands_help(self): """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield "=" * len(header) for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)): yield p yield "" for subc, (_, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield "" def emit_help_epilogue(self, classes): """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield "" def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print("\n".join(self.emit_help(classes=classes))) def emit_help(self, classes=False): """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ yield from self.emit_description() yield from self.emit_subcommands_help() yield from self.emit_options_help() if classes: help_classes = self._classes_with_config_traits() if help_classes: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield "" for cls in help_classes: yield cls.class_get_help() yield "" yield from self.emit_examples() yield from self.emit_help_epilogue(classes) def document_config_options(self): """Generate rST format documentation for the config options this application Returns a multiline string. """ return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self): """Print the application description.""" print("\n".join(self.emit_description())) def emit_description(self): """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__ or ""): yield p yield "" def print_examples(self): """Print usage and examples (see `emit_examples()`).""" print("\n".join(self.emit_examples())) def emit_examples(self): """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield "" yield indent(dedent(self.examples.strip())) yield "" def print_version(self): """Print the version string.""" print(self.version) def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" val = self.subcommands.get(subc) assert val is not None subapp, _ = val if isinstance(subapp, str): subapp = import_item(subapp) # Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) # type:ignore[call-arg] else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self): """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases: t.Dict[str, str] = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split(".", 1) # type:ignore children = mro_tree[cls] # type:ignore[index] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] # type:ignore[assignment] if not isinstance(aliases, tuple): alias = (alias,) # type:ignore[assignment] for al in alias: aliases[al] = ".".join([cls, trait]) # type:ignore[list-item] # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag: t.Dict[t.Any, t.Any] = {} for cls, subdict in flagdict.items(): # type:ignore children = mro_tree[cls] # type:ignore[index] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] # type:ignore[assignment] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): key = (key,) for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader(self, argv, aliases, flags, classes): return KVArgParseConfigLoader( argv, aliases, flags, classes=classes, log=self.log, subcommands=self.subcommands ) def _get_sys_argv(cls, check_argcomplete: bool = False) -> t.List[str]: """Get `sys.argv` or equivalent from `argcomplete` `argcomplete`'s strategy is to call the python script with no arguments, so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed and determine what completions are available. On the other hand, `traitlet`'s subcommand-handling strategy is to check ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically load the subcommand app and initialize it with ``sys.argv[1:]``. This helper method helps to take the current tokens for `argcomplete` and pass them through as `argv`. """ if check_argcomplete and "_ARGCOMPLETE" in os.environ: try: from traitlets.config.argcomplete_config import get_argcomplete_cwords cwords = get_argcomplete_cwords() assert cwords is not None return cwords except (ImportError, ModuleNotFoundError): pass return sys.argv def _handle_argcomplete_for_subcommand(cls): """Helper for `argcomplete` to recognize `traitlets` subcommands `argcomplete` does not know that `traitlets` has already consumed subcommands, as it only "sees" the final `argparse.ArgumentParser` that is constructed. (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.) We explicitly manipulate the environment variables used internally by `argcomplete` to get it to skip over the subcommand tokens. """ if "_ARGCOMPLETE" not in os.environ: return try: from traitlets.config.argcomplete_config import increment_argcomplete_index increment_argcomplete_index() except (ImportError, ModuleNotFoundError): pass def parse_command_line(self, argv=None): """Parse the command line arguments.""" assert not isinstance(argv, str) if argv is None: argv = self._get_sys_argv(check_argcomplete=bool(self.subcommands))[1:] self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == "help": # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ["-h"] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r"^\w(\-?\w)*$", subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter self._handle_argcomplete_for_subcommand() return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[: argv.index("--")] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ("-h", "--help-all", "--help")): self.print_help("--help-all" in interpreted_argv) self.exit(0) if "--version" in interpreted_argv or "-V" in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = tuple(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for current in reversed(path): # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + ".py", path=current, log=log) if log: log.debug("Looking for %s in %s", basefilename, current or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + ".json", path=current, log=log) loaded: t.List[t.Any] = [] filenames: t.List[str] = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), ) ) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) def loaded_config_files(self): """Currently loaded configuration files""" return self._loaded_config_files[:] def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for (config, fname) in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if ( fname not in self._loaded_config_files ): # only add to list of loaded files if not previously loaded self._loaded_config_files.append(fname) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits(self, classes=None): """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes) ) def is_any_parent_included(cls): return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) # Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items() ) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes=None): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append("") lines.append("c = get_config() #" + "noqa") lines.append("") classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return "\n".join(lines) def close_handlers(self): if getattr(self, "_logging_configured", False): # don't attempt to close handlers unless they have been opened # (note accessing self.log.handlers will create handlers if they # have not yet been initialised) for handler in self.log.handlers: with suppress(Exception): handler.close() self._logging_configured = False def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) self.close_handlers() sys.exit(exit_status) def __del__(self): self.close_handlers() def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start() The provided code snippet includes necessary dependencies for implementing the `enable_gui` function. Write a Python function `def enable_gui(gui, kernel=None)` to solve the following problem: Enable integration with a given GUI Here is the function: def enable_gui(gui, kernel=None): """Enable integration with a given GUI""" if gui not in loop_map: e = f"Invalid GUI request {gui!r}, valid ones are:{loop_map.keys()}" raise ValueError(e) if kernel is None: if Application.initialized(): kernel = getattr(Application.instance(), "kernel", None) if kernel is None: msg = ( "You didn't specify a kernel," " and no IPython Application with a kernel appears to be running." ) raise RuntimeError(msg) if gui is None: # User wants to turn off integration; clear any evidence if Qt was the last one. if hasattr(kernel, 'app'): delattr(kernel, 'app') else: if gui.startswith('qt'): # Prepare the kernel here so any exceptions are displayed in the client. make_qt_app_for_kernel(gui, kernel) loop = loop_map[gui] if loop and kernel.eventloop is not None and kernel.eventloop is not loop: msg = "Cannot activate multiple GUI eventloops" raise RuntimeError(msg) kernel.eventloop = loop # We set `eventloop`; the function the user chose is executed in `Kernel.enter_eventloop`, thus # any exceptions raised during the event loop will not be shown in the client.
Enable integration with a given GUI
171,476
import math import numbers import re import types from binascii import b2a_base64 from datetime import date, datetime from jupyter_client._version import version_info as jupyter_client_version The provided code snippet includes necessary dependencies for implementing the `encode_images` function. Write a Python function `def encode_images(format_dict)` to solve the following problem: b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded. Here is the function: def encode_images(format_dict): """b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded. """ # no need for handling of ambiguous bytestrings on Python 3, # where bytes objects always represent binary data and thus # base64-encoded. return format_dict
b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded.
171,477
import math import numbers import re import types from binascii import b2a_base64 from datetime import date, datetime from jupyter_client._version import version_info as jupyter_client_version next_attr_name = "__next__" ISO8601 = "%Y-%m-%dT%H:%M:%S.%f" datetime.strptime("1", "%d") JUPYTER_CLIENT_MAJOR_VERSION = jupyter_client_version[0] class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... if sys.version_info >= (3, 8): def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def ctime(self) -> str: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... def __le__(self, other: date) -> bool: ... def __lt__(self, other: date) -> bool: ... def __ge__(self, other: date) -> bool: ... def __gt__(self, other: date) -> bool: ... if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> date: ... def __radd__(self, other: timedelta) -> date: ... def __sub__(self, other: timedelta) -> date: ... def __sub__(self, other: date) -> timedelta: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... The provided code snippet includes necessary dependencies for implementing the `json_clean` function. Write a Python function `def json_clean(obj)` to solve the following problem: Deprecated, this is a no-op for jupyter-client>=7. Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later. Here is the function: def json_clean(obj): # pragma: no cover """Deprecated, this is a no-op for jupyter-client>=7. Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later. """ if int(JUPYTER_CLIENT_MAJOR_VERSION) >= 7: return obj # types that are 'atomic' and ok in json as-is. atomic_ok = (str, type(None)) # containers that we need to convert into lists container_to_list = (tuple, set, types.GeneratorType) # Since bools are a subtype of Integrals, which are a subtype of Reals, # we have to check them in that order. if isinstance(obj, bool): return obj if isinstance(obj, numbers.Integral): # cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598) return int(obj) if isinstance(obj, numbers.Real): # cast out-of-range floats to their reprs if math.isnan(obj) or math.isinf(obj): return repr(obj) return float(obj) if isinstance(obj, atomic_ok): return obj if isinstance(obj, bytes): # unanmbiguous binary data is base64-encoded # (this probably should have happened upstream) return b2a_base64(obj).decode("ascii") if isinstance(obj, container_to_list) or ( hasattr(obj, "__iter__") and hasattr(obj, next_attr_name) ): obj = list(obj) if isinstance(obj, list): return [json_clean(x) for x in obj] if isinstance(obj, dict): # First, validate that the dict won't lose data in conversion due to # key collisions after stringification. This can happen with keys like # True and 'true' or 1 and '1', which collide in JSON. nkeys = len(obj) nkeys_collapsed = len(set(map(str, obj))) if nkeys != nkeys_collapsed: msg = ( "dict cannot be safely converted to JSON: " "key collision would lead to dropped values" ) raise ValueError(msg) # If all OK, proceed by making the new dict that will be json-safe out = {} for k, v in obj.items(): out[str(k)] = json_clean(v) return out if isinstance(obj, (datetime, date)): return obj.strftime(ISO8601) # we don't understand it, it's probably an unserializable object raise ValueError("Can't clean for JSON: %r" % obj)
Deprecated, this is a no-op for jupyter-client>=7. Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later.
171,478
import asyncio import builtins import getpass import os import signal import sys import threading import typing as t from contextlib import contextmanager from functools import partial import comm from IPython.core import release from IPython.utils.tokenutil import line_at_cursor, token_at_cursor from traitlets import Any, Bool, HasTraits, Instance, List, Type, observe, observe_compat from zmq.eventloop.zmqstream import ZMQStream from .comm.comm import BaseComm from .comm.manager import CommManager from .compiler import XCachingCompiler from .debugger import Debugger, _is_debugpy_available from .eventloops import _use_appnope from .kernelbase import Kernel as KernelBase from .kernelbase import _accepts_cell_id from .zmqshell import ZMQInteractiveShell class BaseComm(comm.base_comm.BaseComm): """The base class for comms.""" kernel: Optional["Kernel"] = None def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys): """Helper for sending a comm message on IOPub""" if not Kernel.initialized(): return data = {} if data is None else data metadata = {} if metadata is None else metadata content = json_clean(dict(data=data, comm_id=self.comm_id, **keys)) if self.kernel is None: self.kernel = Kernel.instance() self.kernel.session.send( self.kernel.iopub_socket, msg_type, content, metadata=json_clean(metadata), parent=self.kernel.get_parent("shell"), ident=self.topic, buffers=buffers, ) The provided code snippet includes necessary dependencies for implementing the `_create_comm` function. Write a Python function `def _create_comm(*args, **kwargs)` to solve the following problem: Create a new Comm. Here is the function: def _create_comm(*args, **kwargs): """Create a new Comm.""" return BaseComm(*args, **kwargs)
Create a new Comm.
171,479
import asyncio import builtins import getpass import os import signal import sys import threading import typing as t from contextlib import contextmanager from functools import partial import comm from IPython.core import release from IPython.utils.tokenutil import line_at_cursor, token_at_cursor from traitlets import Any, Bool, HasTraits, Instance, List, Type, observe, observe_compat from zmq.eventloop.zmqstream import ZMQStream from .comm.comm import BaseComm from .comm.manager import CommManager from .compiler import XCachingCompiler from .debugger import Debugger, _is_debugpy_available from .eventloops import _use_appnope from .kernelbase import Kernel as KernelBase from .kernelbase import _accepts_cell_id from .zmqshell import ZMQInteractiveShell _comm_lock = threading.Lock() _comm_manager: t.Optional[CommManager] = None class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable): """A comm manager.""" kernel = traitlets.Instance("ipykernel.kernelbase.Kernel") comms = traitlets.Dict() targets = traitlets.Dict() def __init__(self, **kwargs): """Initialize the manager.""" # CommManager doesn't take arguments, so we explicitly forward arguments comm.base_comm.CommManager.__init__(self) traitlets.config.LoggingConfigurable.__init__(self, **kwargs) def comm_open(self, stream, ident, msg): """Handler for comm_open messages""" # This is for backward compatibility, the comm_open creates a a new ipykernel.comm.Comm # but we should let the base class create the comm with comm.create_comm in a major release content = msg["content"] comm_id = content["comm_id"] target_name = content["target_name"] f = self.targets.get(target_name, None) comm = Comm( comm_id=comm_id, primary=False, target_name=target_name, show_warning=False, ) self.register_comm(comm) if f is None: logger.error("No such comm target registered: %s", target_name) else: try: f(comm, msg) return except Exception: logger.error("Exception opening comm with target: %s", target_name, exc_info=True) # Failure. try: comm.close() except Exception: logger.error( """Could not close comm during `comm_open` failure clean-up. The comm may not have been opened yet.""", exc_info=True, ) The provided code snippet includes necessary dependencies for implementing the `_get_comm_manager` function. Write a Python function `def _get_comm_manager(*args, **kwargs)` to solve the following problem: Create a new CommManager. Here is the function: def _get_comm_manager(*args, **kwargs): """Create a new CommManager.""" global _comm_manager # noqa if _comm_manager is None: with _comm_lock: if _comm_manager is None: _comm_manager = CommManager(*args, **kwargs) return _comm_manager
Create a new CommManager.
171,480
import warnings warnings.warn( "ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub", DeprecationWarning, stacklevel=2, ) from traitlets import Any, CBytes, Dict, Instance from traitlets.config import Configurable from ipykernel.jsonutil import json_clean from jupyter_client.session import Session, extract_header class ZMQInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for ZMQ.""" displayhook_class = Type(ZMQShellDisplayHook) display_pub_class = Type(ZMQDisplayPublisher) data_pub_class = Any() # type:ignore[assignment] kernel = Any() parent_header = Any() def _default_banner1(self): return default_banner # Override the traitlet in the parent class, because there's no point using # readline for the kernel. Can be removed when the readline code is moved # to the terminal frontend. readline_use = CBool(False) # autoindent has no meaning in a zmqshell, and attempting to enable it # will print a warning in the absence of readline. autoindent = CBool(False) exiter = Instance(ZMQExitAutocall) def _default_exiter(self): return ZMQExitAutocall(self) def _update_exit_now(self, change): """stop eventloop when exit_now fires""" if change["new"]: if hasattr(self.kernel, "io_loop"): loop = self.kernel.io_loop loop.call_later(0.1, loop.stop) if self.kernel.eventloop: exit_hook = getattr(self.kernel.eventloop, "exit_hook", None) if exit_hook: exit_hook(self.kernel) keepkernel_on_exit = None # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no # interactive input being read; we provide event loop support in ipkernel def enable_gui(self, gui): """Enable a given guil.""" from .eventloops import enable_gui as real_enable_gui try: real_enable_gui(gui) self.active_eventloop = gui except ValueError as e: raise UsageError("%s" % e) from e def init_environment(self): """Configure the user's environment.""" env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env["TERM"] = "xterm-color" env["CLICOLOR"] = "1" # These two add terminal color in tools that support it. env["FORCE_COLOR"] = "1" env["CLICOLOR_FORCE"] = "1" # Since normal pagers don't work at all (over pexpect we don't have # single-key control of the subprocess), try to disable paging in # subprocesses as much as possible. env["PAGER"] = "cat" env["GIT_PAGER"] = "cat" def init_hooks(self): """Initialize hooks.""" super().init_hooks() self.set_hook("show_in_pager", page.as_hook(payloadpage.page), 99) def init_data_pub(self): """Delay datapub init until request, for deprecation warnings""" pass def data_pub(self): if not hasattr(self, "_data_pub"): warnings.warn( "InteractiveShell.data_pub is deprecated outside IPython parallel.", DeprecationWarning, stacklevel=2, ) self._data_pub = self.data_pub_class(parent=self) # type:ignore[has-type] self._data_pub.session = self.display_pub.session self._data_pub.pub_socket = self.display_pub.pub_socket return self._data_pub def data_pub(self, pub): self._data_pub = pub def ask_exit(self): """Engage the exit actions.""" self.exit_now = not self.keepkernel_on_exit payload = dict( source="ask_exit", keepkernel=self.keepkernel_on_exit, ) self.payload_manager.write_payload(payload) def run_cell(self, *args, **kwargs): """Run a cell.""" self._last_traceback = None return super().run_cell(*args, **kwargs) def _showtraceback(self, etype, evalue, stb): # try to preserve ordering of tracebacks and print statements sys.stdout.flush() sys.stderr.flush() exc_content = { "traceback": stb, "ename": str(etype.__name__), "evalue": str(evalue), } dh = self.displayhook # Send exception info over pub socket for other clients than the caller # to pick up topic = None if dh.topic: topic = dh.topic.replace(b"execute_result", b"error") dh.session.send( dh.pub_socket, "error", json_clean(exc_content), dh.parent_header, ident=topic, ) # FIXME - Once we rely on Python 3, the traceback is stored on the # exception object, so we shouldn't need to store it here. self._last_traceback = stb def set_next_input(self, text, replace=False): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source="set_next_input", text=text, replace=replace, ) self.payload_manager.write_payload(payload) def set_parent(self, parent): """Set the parent header for associating output with its triggering input""" self.parent_header = parent self.displayhook.set_parent(parent) self.display_pub.set_parent(parent) if hasattr(self, "_data_pub"): self.data_pub.set_parent(parent) try: sys.stdout.set_parent(parent) # type:ignore[attr-defined] except AttributeError: pass try: sys.stderr.set_parent(parent) # type:ignore[attr-defined] except AttributeError: pass def get_parent(self): """Get the parent header.""" return self.parent_header def init_magics(self): """Initialize magics.""" super().init_magics() self.register_magics(KernelMagics) self.magics_manager.register_alias("ed", "edit") def init_virtualenv(self): """Initialize virtual environment.""" # Overridden not to do virtualenv detection, because it's probably # not appropriate in a kernel. To use a kernel in a virtualenv, install # it inside the virtualenv. # https://ipython.readthedocs.io/en/latest/install/kernel_install.html pass def system_piped(self, cmd): """Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than simple text. """ if cmd.rstrip().endswith("&"): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always just call # os.system() or use ip.system=ip.system_raw # if they really want a background process. msg = "Background processes not supported." raise OSError(msg) # we explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. # Also, protect system call from UNC paths on Windows here too # as is done in InteractiveShell.system_raw if sys.platform == "win32": cmd = self.var_expand(cmd, depth=1) from IPython.utils._process_win32 import AvoidUNCPath with AvoidUNCPath() as path: if path is not None: cmd = f"pushd {path} &&{cmd}" self.user_ns["_exit_code"] = system(cmd) else: self.user_ns["_exit_code"] = system(self.var_expand(cmd, depth=1)) # Ensure new system_piped implementation is used system = system_piped The provided code snippet includes necessary dependencies for implementing the `publish_data` function. Write a Python function `def publish_data(data)` to solve the following problem: publish a data_message on the IOPub channel Parameters ---------- data : dict The data to be published. Think of it as a namespace. Here is the function: def publish_data(data): """publish a data_message on the IOPub channel Parameters ---------- data : dict The data to be published. Think of it as a namespace. """ warnings.warn( "ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub", DeprecationWarning, stacklevel=2, ) from ipykernel.zmqshell import ZMQInteractiveShell ZMQInteractiveShell.instance().data_pub.publish_data(data)
publish a data_message on the IOPub channel Parameters ---------- data : dict The data to be published. Think of it as a namespace.
171,481
import sys from IPython.utils.frame import extract_module_locals from .kernelapp import IPKernelApp def extract_module_locals(depth=0): """Returns (module, locals) of the function `depth` frames away from the caller""" f = sys._getframe(depth + 1) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals) class IPKernelApp(BaseIPythonApplication, InteractiveShellApp, ConnectionFileMixin): """The IPYKernel application class.""" name = "ipython-kernel" aliases = Dict(kernel_aliases) # type:ignore[assignment] flags = Dict(kernel_flags) # type:ignore[assignment] classes = [IPythonKernel, ZMQInteractiveShell, ProfileDir, Session] # the kernel class, as an importstring kernel_class = Type( "ipykernel.ipkernel.IPythonKernel", klass="ipykernel.kernelbase.Kernel", help="""The Kernel subclass to be used. This should allow easy re-use of the IPKernelApp entry point to configure and launch kernels other than IPython's own. """, ).tag(config=True) kernel = Any() poller = Any() # don't restrict this even though current pollers are all Threads heartbeat = Instance(Heartbeat, allow_none=True) context: Optional[zmq.Context] = Any() # type:ignore[assignment] shell_socket = Any() control_socket = Any() debugpy_socket = Any() debug_shell_socket = Any() stdin_socket = Any() iopub_socket = Any() iopub_thread = Any() control_thread = Any() _ports = Dict() subcommands = { "install": ( "ipykernel.kernelspec.InstallIPythonKernelSpecApp", "Install the IPython kernel", ), } # connection info: connection_dir = Unicode() def _default_connection_dir(self): return jupyter_runtime_dir() def abs_connection_file(self): if os.path.basename(self.connection_file) == self.connection_file: return os.path.join(self.connection_dir, self.connection_file) else: return self.connection_file # streams, etc. no_stdout = Bool(False, help="redirect stdout to the null device").tag(config=True) no_stderr = Bool(False, help="redirect stderr to the null device").tag(config=True) trio_loop = Bool(False, help="Set main event loop.").tag(config=True) quiet = Bool(True, help="Only send stdout/stderr to output stream").tag(config=True) outstream_class = DottedObjectName( "ipykernel.iostream.OutStream", help="The importstring for the OutStream factory", allow_none=True, ).tag(config=True) displayhook_class = DottedObjectName( "ipykernel.displayhook.ZMQDisplayHook", help="The importstring for the DisplayHook factory" ).tag(config=True) capture_fd_output = Bool( True, help="""Attempt to capture and forward low-level output, e.g. produced by Extension libraries. """, ).tag(config=True) # polling parent_handle = Integer( int(os.environ.get("JPY_PARENT_PID") or 0), help="""kill this process if its parent dies. On Windows, the argument specifies the HANDLE of the parent process, otherwise it is simply boolean. """, ).tag(config=True) interrupt = Integer( int(os.environ.get("JPY_INTERRUPT_EVENT") or 0), help="""ONLY USED ON WINDOWS Interrupt this process when the parent is signaled. """, ).tag(config=True) def init_crash_handler(self): """Initialize the crash handler.""" sys.excepthook = self.excepthook def excepthook(self, etype, evalue, tb): """Handle an exception.""" # write uncaught traceback to 'real' stderr, not zmq-forwarder traceback.print_exception(etype, evalue, tb, file=sys.__stderr__) def init_poller(self): """Initialize the poller.""" if sys.platform == "win32": if self.interrupt or self.parent_handle: self.poller = ParentPollerWindows(self.interrupt, self.parent_handle) elif self.parent_handle and self.parent_handle != 1: # PID 1 (init) is special and will never go away, # only be reassigned. # Parent polling doesn't work if ppid == 1 to start with. self.poller = ParentPollerUnix() def _try_bind_socket(self, s, port): iface = f"{self.transport}://{self.ip}" if self.transport == "tcp": if port <= 0: port = s.bind_to_random_port(iface) else: s.bind("tcp://%s:%i" % (self.ip, port)) elif self.transport == "ipc": if port <= 0: port = 1 path = "%s-%i" % (self.ip, port) while os.path.exists(path): port = port + 1 path = "%s-%i" % (self.ip, port) else: path = "%s-%i" % (self.ip, port) s.bind("ipc://%s" % path) return port def _bind_socket(self, s, port): try: win_in_use = errno.WSAEADDRINUSE # type:ignore[attr-defined] except AttributeError: win_in_use = None # Try up to 100 times to bind a port when in conflict to avoid # infinite attempts in bad setups max_attempts = 1 if port else 100 for attempt in range(max_attempts): try: return self._try_bind_socket(s, port) except zmq.ZMQError as ze: # Raise if we have any error not related to socket binding if ze.errno != errno.EADDRINUSE and ze.errno != win_in_use: raise if attempt == max_attempts - 1: raise def write_connection_file(self): """write connection info to JSON file""" cf = self.abs_connection_file self.log.debug("Writing connection file: %s", cf) write_connection_file( cf, ip=self.ip, key=self.session.key, transport=self.transport, shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port, iopub_port=self.iopub_port, control_port=self.control_port, ) def cleanup_connection_file(self): """Clean up our connection file.""" cf = self.abs_connection_file self.log.debug("Cleaning up connection file: %s", cf) try: os.remove(cf) except OSError: pass self.cleanup_ipc_files() def init_connection_file(self): """Initialize our connection file.""" if not self.connection_file: self.connection_file = "kernel-%s.json" % os.getpid() try: self.connection_file = filefind(self.connection_file, [".", self.connection_dir]) except OSError: self.log.debug("Connection file not found: %s", self.connection_file) # This means I own it, and I'll create it in this directory: os.makedirs(os.path.dirname(self.abs_connection_file), mode=0o700, exist_ok=True) # Also, I will clean it up: atexit.register(self.cleanup_connection_file) return try: self.load_connection_file() except Exception: self.log.error( "Failed to load connection file: %r", self.connection_file, exc_info=True ) self.exit(1) def init_sockets(self): """Create a context, a session, and the kernel sockets.""" self.log.info("Starting the kernel at pid: %i", os.getpid()) assert self.context is None, "init_sockets cannot be called twice!" self.context = context = zmq.Context() atexit.register(self.close) self.shell_socket = context.socket(zmq.ROUTER) self.shell_socket.linger = 1000 self.shell_port = self._bind_socket(self.shell_socket, self.shell_port) self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port) self.stdin_socket = context.socket(zmq.ROUTER) self.stdin_socket.linger = 1000 self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port) self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port) if hasattr(zmq, "ROUTER_HANDOVER"): # set router-handover to workaround zeromq reconnect problems # in certain rare circumstances # see ipython/ipykernel#270 and zeromq/libzmq#2892 self.shell_socket.router_handover = self.stdin_socket.router_handover = 1 self.init_control(context) self.init_iopub(context) def init_control(self, context): """Initialize the control channel.""" self.control_socket = context.socket(zmq.ROUTER) self.control_socket.linger = 1000 self.control_port = self._bind_socket(self.control_socket, self.control_port) self.log.debug("control ROUTER Channel on port: %i" % self.control_port) self.debugpy_socket = context.socket(zmq.STREAM) self.debugpy_socket.linger = 1000 self.debug_shell_socket = context.socket(zmq.DEALER) self.debug_shell_socket.linger = 1000 if self.shell_socket.getsockopt(zmq.LAST_ENDPOINT): self.debug_shell_socket.connect(self.shell_socket.getsockopt(zmq.LAST_ENDPOINT)) if hasattr(zmq, "ROUTER_HANDOVER"): # set router-handover to workaround zeromq reconnect problems # in certain rare circumstances # see ipython/ipykernel#270 and zeromq/libzmq#2892 self.control_socket.router_handover = 1 self.control_thread = ControlThread(daemon=True) def init_iopub(self, context): """Initialize the iopub channel.""" self.iopub_socket = context.socket(zmq.PUB) self.iopub_socket.linger = 1000 self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port) self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port) self.configure_tornado_logger() self.iopub_thread = IOPubThread(self.iopub_socket, pipe=True) self.iopub_thread.start() # backward-compat: wrap iopub socket API in background thread self.iopub_socket = self.iopub_thread.background_socket def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port) self.heartbeat.start() def close(self): """Close zmq sockets in an orderly fashion""" # un-capture IO before we start closing channels self.reset_io() self.log.info("Cleaning up sockets") if self.heartbeat: self.log.debug("Closing heartbeat channel") self.heartbeat.context.term() if self.iopub_thread: self.log.debug("Closing iopub channel") self.iopub_thread.stop() self.iopub_thread.close() if self.control_thread and self.control_thread.is_alive(): self.log.debug("Closing control thread") self.control_thread.stop() self.control_thread.join() if self.debugpy_socket and not self.debugpy_socket.closed: self.debugpy_socket.close() if self.debug_shell_socket and not self.debug_shell_socket.closed: self.debug_shell_socket.close() for channel in ("shell", "control", "stdin"): self.log.debug("Closing %s channel", channel) socket = getattr(self, channel + "_socket", None) if socket and not socket.closed: socket.close() self.log.debug("Terminating zmq context") if self.context: self.context.term() self.log.debug("Terminated zmq context") def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if ( basename == self.connection_file or os.path.dirname(self.connection_file) == self.connection_dir ): # use shortname tail = basename else: tail = self.connection_file lines = [ "To connect another client to this kernel, use:", " --existing %s" % tail, ] # log connection info # info-level, so often not shown. # frontends should use the %connect_info magic # to see the connection info for line in lines: self.log.info(line) # also raw print to the terminal if no parent_handle (`ipython kernel`) # unless log-level is CRITICAL (--quiet) if not self.parent_handle and int(self.log_level) < logging.CRITICAL: print(_ctrl_c_message, file=sys.__stdout__) for line in lines: print(line, file=sys.__stdout__) self._ports = dict( shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port, control=self.control_port, ) def init_blackhole(self): """redirects stdout/stderr to devnull if necessary""" if self.no_stdout or self.no_stderr: blackhole = open(os.devnull, "w") # noqa if self.no_stdout: sys.stdout = sys.__stdout__ = blackhole # type:ignore if self.no_stderr: sys.stderr = sys.__stderr__ = blackhole # type:ignore def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) if sys.stdout is not None: sys.stdout.flush() e_stdout = None if self.quiet else sys.__stdout__ e_stderr = None if self.quiet else sys.__stderr__ if not self.capture_fd_output: outstream_factory = partial(outstream_factory, watchfd=False) sys.stdout = outstream_factory(self.session, self.iopub_thread, "stdout", echo=e_stdout) if sys.stderr is not None: sys.stderr.flush() sys.stderr = outstream_factory(self.session, self.iopub_thread, "stderr", echo=e_stderr) if hasattr(sys.stderr, "_original_stdstream_copy"): for handler in self.log.handlers: if isinstance(handler, StreamHandler) and (handler.stream.buffer.fileno() == 2): self.log.debug("Seeing logger to stderr, rerouting to raw filedescriptor.") handler.stream = TextIOWrapper( FileIO( sys.stderr._original_stdstream_copy, "w", ) ) if self.displayhook_class: displayhook_factory = import_item(str(self.displayhook_class)) self.displayhook = displayhook_factory(self.session, self.iopub_socket) sys.displayhook = self.displayhook self.patch_io() def reset_io(self): """restore original io restores state after init_io """ sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.displayhook = sys.__displayhook__ def patch_io(self): """Patch important libraries that can't handle sys.stdout forwarding""" try: import faulthandler except ImportError: pass else: # Warning: this is a monkeypatch of `faulthandler.enable`, watch for possible # updates to the upstream API and update accordingly (up-to-date as of Python 3.5): # https://docs.python.org/3/library/faulthandler.html#faulthandler.enable # change default file to __stderr__ from forwarded stderr faulthandler_enable = faulthandler.enable def enable(file=sys.__stderr__, all_threads=True, **kwargs): return faulthandler_enable(file=file, all_threads=all_threads, **kwargs) faulthandler.enable = enable if hasattr(faulthandler, "register"): faulthandler_register = faulthandler.register def register(signum, file=sys.__stderr__, all_threads=True, chain=False, **kwargs): return faulthandler_register( signum, file=file, all_threads=all_threads, chain=chain, **kwargs ) faulthandler.register = register def init_signal(self): """Initialize the signal handler.""" signal.signal(signal.SIGINT, signal.SIG_IGN) def init_kernel(self): """Create the Kernel object itself""" shell_stream = ZMQStream(self.shell_socket) control_stream = ZMQStream(self.control_socket, self.control_thread.io_loop) debugpy_stream = ZMQStream(self.debugpy_socket, self.control_thread.io_loop) self.control_thread.start() kernel_factory = self.kernel_class.instance kernel = kernel_factory( parent=self, session=self.session, control_stream=control_stream, debugpy_stream=debugpy_stream, debug_shell_socket=self.debug_shell_socket, shell_stream=shell_stream, control_thread=self.control_thread, iopub_thread=self.iopub_thread, iopub_socket=self.iopub_socket, stdin_socket=self.stdin_socket, log=self.log, profile_dir=self.profile_dir, user_ns=self.user_ns, ) kernel.record_ports({name + "_port": port for name, port in self._ports.items()}) self.kernel = kernel # Allow the displayhook to get the execution count self.displayhook.get_execution_count = lambda: kernel.execution_count def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" # Register inline backend as default # this is higher priority than matplotlibrc, # but lower priority than anything else (mpl.use() for instance). # This only affects matplotlib >= 1.5 if not os.environ.get("MPLBACKEND"): os.environ["MPLBACKEND"] = "module://matplotlib_inline.backend_inline" # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` # to ensure that any exception is printed straight to stderr. # Normally _showtraceback associates the reply with an execution, # which means frontends will never draw it, as this exception # is not associated with any execute request. shell = self.shell assert shell is not None _showtraceback = shell._showtraceback try: # replace error-sending traceback with stderr def print_tb(etype, evalue, stb): print("GUI event loop or pylab initialization failed", file=sys.stderr) assert shell is not None print(shell.InteractiveTB.stb2text(stb), file=sys.stderr) shell._showtraceback = print_tb InteractiveShellApp.init_gui_pylab(self) finally: shell._showtraceback = _showtraceback def init_shell(self): """Initialize the shell channel.""" self.shell = getattr(self.kernel, "shell", None) if self.shell: self.shell.configurables.append(self) def configure_tornado_logger(self): """Configure the tornado logging.Logger. Must set up the tornado logger or else tornado will call basicConfig for the root logger which makes the root logger go to the real sys.stderr instead of the capture streams. This function mimics the setup of logging.basicConfig. """ logger = logging.getLogger("tornado") handler = logging.StreamHandler() formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) def _init_asyncio_patch(self): """set default asyncio policy to be compatible with tornado Tornado 6 (at least) is not compatible with the default asyncio implementation on Windows Pick the older SelectorEventLoopPolicy on Windows if the known-incompatible default policy is in use. Support for Proactor via a background thread is available in tornado 6.1, but it is still preferable to run the Selector in the main thread instead of the background. do this as early as possible to make it a low priority and overrideable ref: https://github.com/tornadoweb/tornado/issues/2608 FIXME: if/when tornado supports the defaults in asyncio without threads, remove and bump tornado requirement for py38. Most likely, this will mean a new Python version where asyncio.ProactorEventLoop supports add_reader and friends. """ if sys.platform.startswith("win") and sys.version_info >= (3, 8): import asyncio try: from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy except ImportError: pass # not affected else: if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy: # WindowsProactorEventLoopPolicy is not compatible with tornado 6 # fallback to the pre-3.8 default of Selector asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) def init_pdb(self): """Replace pdb with IPython's version that is interruptible. With the non-interruptible version, stopping pdb() locks up the kernel in a non-recoverable state. """ import pdb # noqa from IPython.core import debugger if hasattr(debugger, "InterruptiblePdb"): # Only available in newer IPython releases: debugger.Pdb = debugger.InterruptiblePdb # type:ignore pdb.Pdb = debugger.Pdb # type:ignore pdb.set_trace = debugger.set_trace # type:ignore[assignment] def initialize(self, argv=None): """Initialize the application.""" self._init_asyncio_patch() super().initialize(argv) if self.subapp is not None: return self.init_pdb() self.init_blackhole() self.init_connection_file() self.init_poller() self.init_sockets() self.init_heartbeat() # writing/displaying connection info must be *after* init_sockets/heartbeat self.write_connection_file() # Log connection info after writing connection file, so that the connection # file is definitely available at the time someone reads the log. self.log_connection_info() self.init_io() try: self.init_signal() except Exception: # Catch exception when initializing signal fails, eg when running the # kernel on a separate thread if int(self.log_level) < logging.CRITICAL: self.log.error("Unable to initialize signal:", exc_info=True) self.init_kernel() # shell init steps self.init_path() self.init_shell() if self.shell: self.init_gui_pylab() self.init_extensions() self.init_code() # flush stdout/stderr, so that anything written to these streams during # initialization do not get associated with the first execution request sys.stdout.flush() sys.stderr.flush() def start(self): """Start the application.""" if self.subapp is not None: return self.subapp.start() if self.poller is not None: self.poller.start() self.kernel.start() self.io_loop = ioloop.IOLoop.current() if self.trio_loop: from ipykernel.trio_runner import TrioRunner tr = TrioRunner() tr.initialize(self.kernel, self.io_loop) try: tr.run() except KeyboardInterrupt: pass else: try: self.io_loop.start() except KeyboardInterrupt: pass The provided code snippet includes necessary dependencies for implementing the `embed_kernel` function. Write a Python function `def embed_kernel(module=None, local_ns=None, **kwargs)` to solve the following problem: Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : dict, optional Further keyword args are relayed to the IPKernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process. Here is the function: def embed_kernel(module=None, local_ns=None, **kwargs): """Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : dict, optional Further keyword args are relayed to the IPKernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process. """ # get the app if it exists, or set it up if it doesn't if IPKernelApp.initialized(): app = IPKernelApp.instance() else: app = IPKernelApp.instance(**kwargs) app.initialize([]) # Undo unnecessary sys module mangling from init_sys_modules. # This would not be necessary if we could prevent it # in the first place by using a different InteractiveShell # subclass, as in the regular embed case. main = app.kernel.shell._orig_sys_modules_main_mod if main is not None: sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main # load the calling scope if not given (caller_module, caller_locals) = extract_module_locals(1) if module is None: module = caller_module if local_ns is None: local_ns = caller_locals app.kernel.user_module = module app.kernel.user_ns = local_ns app.shell.set_completer_frame() app.start()
Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : dict, optional Further keyword args are relayed to the IPKernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process.
171,482
import warnings import pickle from itertools import chain from jupyter_client.session import MAX_BYTES, MAX_ITEMS def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized buffer_threshold : int The threshold (in bytes) for pulling out data buffers to avoid pickling them. item_threshold : int The maximum number of items over which canning will iterate. Containers (lists, dicts) larger than this will be pickled without introspection. Returns ------- [bufs] : list of buffers representing the serialized object. """ buffers = [] if istype(obj, sequence_types) and len(obj) < item_threshold: cobj = can_sequence(obj) for c in cobj: buffers.extend(_extract_buffers(c, buffer_threshold)) elif istype(obj, dict) and len(obj) < item_threshold: cobj = {} for k in sorted(obj): c = can(obj[k]) buffers.extend(_extract_buffers(c, buffer_threshold)) cobj[k] = c else: cobj = can(obj) buffers.extend(_extract_buffers(cobj, buffer_threshold)) buffers.insert(0, pickle.dumps(cobj, PICKLE_PROTOCOL)) return buffers class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... PICKLE_PROTOCOL = pickle.DEFAULT_PROTOCOL def can(obj): """prepare an object for pickling""" import_needed = False for cls, canner in can_map.items(): if isinstance(cls, str): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: # perform can_map imports, then try again # this will usually only happen once _import_mapping(can_map, _original_can_map) return can(obj) return obj MAX_ITEMS = 64 MAX_BYTES = 1024 The provided code snippet includes necessary dependencies for implementing the `pack_apply_message` function. Write a Python function `def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS)` to solve the following problem: pack up a function, args, and kwargs to be sent over the wire Each element of args/kwargs will be canned for special treatment, but inspection will not go any deeper than that. Any object whose data is larger than `threshold` will not have their data copied (only numpy arrays and bytes/buffers support zero-copy) Message will be a list of bytes/buffers of the format: [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ] With length at least two + len(args) + len(kwargs) Here is the function: def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS): """pack up a function, args, and kwargs to be sent over the wire Each element of args/kwargs will be canned for special treatment, but inspection will not go any deeper than that. Any object whose data is larger than `threshold` will not have their data copied (only numpy arrays and bytes/buffers support zero-copy) Message will be a list of bytes/buffers of the format: [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ] With length at least two + len(args) + len(kwargs) """ arg_bufs = list( chain.from_iterable(serialize_object(arg, buffer_threshold, item_threshold) for arg in args) ) kw_keys = sorted(kwargs.keys()) kwarg_bufs = list( chain.from_iterable( serialize_object(kwargs[key], buffer_threshold, item_threshold) for key in kw_keys ) ) info = dict(nargs=len(args), narg_bufs=len(arg_bufs), kw_keys=kw_keys) msg = [pickle.dumps(can(f), PICKLE_PROTOCOL)] msg.append(pickle.dumps(info, PICKLE_PROTOCOL)) msg.extend(arg_bufs) msg.extend(kwarg_bufs) return msg
pack up a function, args, and kwargs to be sent over the wire Each element of args/kwargs will be canned for special treatment, but inspection will not go any deeper than that. Any object whose data is larger than `threshold` will not have their data copied (only numpy arrays and bytes/buffers support zero-copy) Message will be a list of bytes/buffers of the format: [ cf, pinfo, <arg_bufs>, <kwarg_bufs> ] With length at least two + len(args) + len(kwargs)
171,483
import warnings import pickle from itertools import chain from jupyter_client.session import MAX_BYTES, MAX_ITEMS def deserialize_object(buffers, g=None): """reconstruct an object serialized by serialize_object from data buffers. Parameters ---------- buffers : list of buffers/bytes g : globals to be used when uncanning Returns ------- (newobj, bufs) : unpacked object, and the list of remaining unused buffers. """ bufs = list(buffers) pobj = bufs.pop(0) canned = pickle.loads(pobj) if istype(canned, sequence_types) and len(canned) < MAX_ITEMS: for c in canned: _restore_buffers(c, bufs) newobj = uncan_sequence(canned, g) elif istype(canned, dict) and len(canned) < MAX_ITEMS: newobj = {} for k in sorted(canned): c = canned[k] _restore_buffers(c, bufs) newobj[k] = uncan(c, g) else: _restore_buffers(canned, bufs) newobj = uncan(canned, g) return newobj, bufs def uncan(obj, g=None): """invert canning""" import_needed = False for cls, uncanner in uncan_map.items(): if isinstance(cls, str): import_needed = True break elif isinstance(obj, cls): return uncanner(obj, g) if import_needed: # perform uncan_map imports, then try again # this will usually only happen once _import_mapping(uncan_map, _original_uncan_map) return uncan(obj, g) return obj The provided code snippet includes necessary dependencies for implementing the `unpack_apply_message` function. Write a Python function `def unpack_apply_message(bufs, g=None, copy=True)` to solve the following problem: unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs Here is the function: def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 2, "not enough buffers!" pf = bufs.pop(0) f = uncan(pickle.loads(pf), g) pinfo = bufs.pop(0) info = pickle.loads(pinfo) arg_bufs, kwarg_bufs = bufs[: info["narg_bufs"]], bufs[info["narg_bufs"] :] args_list = [] for _ in range(info["nargs"]): arg, arg_bufs = deserialize_object(arg_bufs, g) args_list.append(arg) args = tuple(args_list) assert not arg_bufs, "Shouldn't be any arg bufs left over" kwargs = {} for key in info["kw_keys"]: kwarg, kwarg_bufs = deserialize_object(kwarg_bufs, g) kwargs[key] = kwarg assert not kwarg_bufs, "Shouldn't be any kwarg bufs left over" return f, args, kwargs
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
171,484
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item The provided code snippet includes necessary dependencies for implementing the `_get_cell_type` function. Write a Python function `def _get_cell_type(a=None)` to solve the following problem: the type of a closure cell doesn't seem to be importable, so just create one Here is the function: def _get_cell_type(a=None): """the type of a closure cell doesn't seem to be importable, so just create one """ def inner(): return a return type(inner.__closure__[0]) # type:ignore[index]
the type of a closure cell doesn't seem to be importable, so just create one
171,485
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item class FunctionType: __closure__: Optional[Tuple[_Cell, ...]] __code__: CodeType __defaults__: Optional[Tuple[Any, ...]] __dict__: Dict[str, Any] __globals__: Dict[str, Any] __name__: str __qualname__: str __annotations__: Dict[str, Any] __kwdefaults__: Dict[str, Any] def __init__( self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... The provided code snippet includes necessary dependencies for implementing the `interactive` function. Write a Python function `def interactive(f)` to solve the following problem: decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). Here is the function: def interactive(f): """decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). """ # build new FunctionType, so it can have the right globals # interactive functions never have closures, that's kind of the point if isinstance(f, FunctionType): mainmod = __import__("__main__") f = FunctionType( f.__code__, mainmod.__dict__, f.__name__, f.__defaults__, ) # associate with __main__ for uncanning f.__module__ = "__main__" return f
decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals().
171,486
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item can_map = { "numpy.ndarray": CannedArray, FunctionType: CannedFunction, bytes: CannedBytes, memoryview: CannedMemoryView, cell_type: CannedCell, class_type: can_class, } class FunctionType: __closure__: Optional[Tuple[_Cell, ...]] __code__: CodeType __defaults__: Optional[Tuple[Any, ...]] __dict__: Dict[str, Any] __globals__: Dict[str, Any] __name__: str __qualname__: str __annotations__: Dict[str, Any] __kwdefaults__: Dict[str, Any] def __init__( self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... The provided code snippet includes necessary dependencies for implementing the `use_dill` function. Write a Python function `def use_dill()` to solve the following problem: use dill to expand serialization support adds support for object methods and closures to serialization. Here is the function: def use_dill(): """use dill to expand serialization support adds support for object methods and closures to serialization. """ # import dill causes most of the magic import dill # dill doesn't work with cPickle, # tell the two relevant modules to use plain pickle global pickle # noqa pickle = dill try: from ipykernel import serialize except ImportError: pass else: serialize.pickle = dill # type:ignore[attr-defined] # disable special function handling, let dill take care of it can_map.pop(FunctionType, None)
use dill to expand serialization support adds support for object methods and closures to serialization.
171,487
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item can_map = { "numpy.ndarray": CannedArray, FunctionType: CannedFunction, bytes: CannedBytes, memoryview: CannedMemoryView, cell_type: CannedCell, class_type: can_class, } class FunctionType: __closure__: Optional[Tuple[_Cell, ...]] __code__: CodeType __defaults__: Optional[Tuple[Any, ...]] __dict__: Dict[str, Any] __globals__: Dict[str, Any] __name__: str __qualname__: str __annotations__: Dict[str, Any] __kwdefaults__: Dict[str, Any] def __init__( self, code: CodeType, globals: Dict[str, Any], name: Optional[str] = ..., argdefs: Optional[Tuple[object, ...]] = ..., closure: Optional[Tuple[_Cell, ...]] = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... The provided code snippet includes necessary dependencies for implementing the `use_cloudpickle` function. Write a Python function `def use_cloudpickle()` to solve the following problem: use cloudpickle to expand serialization support adds support for object methods and closures to serialization. Here is the function: def use_cloudpickle(): """use cloudpickle to expand serialization support adds support for object methods and closures to serialization. """ import cloudpickle global pickle # noqa pickle = cloudpickle try: from ipykernel import serialize except ImportError: pass else: serialize.pickle = cloudpickle # type:ignore[attr-defined] # disable special function handling, let cloudpickle take care of it can_map.pop(FunctionType, None)
use cloudpickle to expand serialization support adds support for object methods and closures to serialization.
171,488
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item class_type = type class CannedClass(CannedObject): """A canned class object.""" def __init__(self, cls): """Initialize the can.""" self._check_type(cls) self.name = cls.__name__ self.old_style = not isinstance(cls, type) self._canned_dict = {} for k, v in cls.__dict__.items(): if k not in ("__weakref__", "__dict__"): self._canned_dict[k] = can(v) mro = [] if self.old_style else cls.mro() self.parents = [can(c) for c in mro[1:]] self.buffers = [] def _check_type(self, obj): assert isinstance(obj, class_type), "Not a class type" def get_object(self, g=None): """Get an object from the can.""" parents = tuple(uncan(p, g) for p in self.parents) return type(self.name, parents, uncan_dict(self._canned_dict, g=g)) The provided code snippet includes necessary dependencies for implementing the `can_class` function. Write a Python function `def can_class(obj)` to solve the following problem: Can a class object. Here is the function: def can_class(obj): """Can a class object.""" if isinstance(obj, class_type) and obj.__module__ == "__main__": return CannedClass(obj) else: return obj
Can a class object.
171,489
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item def istype(obj, check): """like isinstance(obj, check), but strict This won't catch subclasses. """ if isinstance(check, tuple): return any(type(obj) is cls for cls in check) else: return type(obj) is check def can(obj): """prepare an object for pickling""" import_needed = False for cls, canner in can_map.items(): if isinstance(cls, str): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: # perform can_map imports, then try again # this will usually only happen once _import_mapping(can_map, _original_can_map) return can(obj) return obj The provided code snippet includes necessary dependencies for implementing the `can_dict` function. Write a Python function `def can_dict(obj)` to solve the following problem: can the *values* of a dict Here is the function: def can_dict(obj): """can the *values* of a dict""" if istype(obj, dict): newobj = {} for k, v in obj.items(): newobj[k] = can(v) return newobj else: return obj
can the *values* of a dict
171,490
import typing import warnings import copy import pickle import sys from types import FunctionType from ipyparallel.serialize import codeutil from traitlets.log import get_logger from traitlets.utils.importstring import import_item def istype(obj, check): """like isinstance(obj, check), but strict This won't catch subclasses. """ if isinstance(check, tuple): return any(type(obj) is cls for cls in check) else: return type(obj) is check def uncan(obj, g=None): """invert canning""" import_needed = False for cls, uncanner in uncan_map.items(): if isinstance(cls, str): import_needed = True break elif isinstance(obj, cls): return uncanner(obj, g) if import_needed: # perform uncan_map imports, then try again # this will usually only happen once _import_mapping(uncan_map, _original_uncan_map) return uncan(obj, g) return obj The provided code snippet includes necessary dependencies for implementing the `uncan_dict` function. Write a Python function `def uncan_dict(obj, g=None)` to solve the following problem: Uncan a dict object. Here is the function: def uncan_dict(obj, g=None): """Uncan a dict object.""" if istype(obj, dict): newobj = {} for k, v in obj.items(): newobj[k] = uncan(v, g) return newobj else: return obj
Uncan a dict object.
171,491
import win32api import win32con import win32evtlog import win32evtlogutil import win32security def ReadLog(computer, logType="Application", dumpEachRecord=0): # read the entire log back. h = win32evtlog.OpenEventLog(computer, logType) numRecords = win32evtlog.GetNumberOfEventLogRecords(h) # print "There are %d records" % numRecords num = 0 while 1: objects = win32evtlog.ReadEventLog( h, win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0, ) if not objects: break for object in objects: # get it for testing purposes, but dont print it. msg = win32evtlogutil.SafeFormatMessage(object, logType) if object.Sid is not None: try: domain, user, typ = win32security.LookupAccountSid( computer, object.Sid ) sidDesc = "%s/%s" % (domain, user) except win32security.error: sidDesc = str(object.Sid) user_desc = "Event associated with user %s" % (sidDesc,) else: user_desc = None if dumpEachRecord: print( "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format()) ) if user_desc: print(user_desc) try: print(msg) except UnicodeError: print("(unicode error printing message: repr() follows...)") print(repr(msg)) num = num + len(objects) if numRecords == num: print("Successfully read all", numRecords, "records") else: print( "Couldn't get all records - reported %d, but found %d" % (numRecords, num) ) print( "(Note that some other app may have written records while we were running!)" ) win32evtlog.CloseEventLog(h)
null
171,492
import win32api import win32con import win32evtlog import win32evtlogutil import win32security def usage(): print("Writes an event to the event log.") print("-w : Dont write any test records.") print("-r : Dont read the event log") print("-c : computerName : Process the log on the specified computer") print("-v : Verbose") print("-t : LogType - Use the specified log - default = 'Application'")
null
171,493
import sys import time import win32api import win32con import win32file import win32gui import win32gui_struct import winnt GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}" def OnDeviceChange(hwnd, msg, wp, lp): # Unpack the 'lp' into the appropriate DEV_BROADCAST_* structure, # using the self-identifying data inside the DEV_BROADCAST_HDR. info = win32gui_struct.UnpackDEV_BROADCAST(lp) print("Device change notification:", wp, str(info)) if ( wp == win32con.DBT_DEVICEQUERYREMOVE and info.devicetype == win32con.DBT_DEVTYP_HANDLE ): # Our handle is stored away in the structure - just close it print("Device being removed - closing handle") win32file.CloseHandle(info.handle) # and cancel our notifications - if it gets plugged back in we get # the same notification and try and close the same handle... win32gui.UnregisterDeviceNotification(info.hdevnotify) return True def TestDeviceNotifications(dir_names): wc = win32gui.WNDCLASS() wc.lpszClassName = "test_devicenotify" wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpfnWndProc = {win32con.WM_DEVICECHANGE: OnDeviceChange} class_atom = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow( wc.lpszClassName, "Testing some devices", # no need for it to be visible. win32con.WS_CAPTION, 100, 100, 900, 900, 0, 0, 0, None, ) hdevs = [] # Watch for all USB device notifications filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE( GUID_DEVINTERFACE_USB_DEVICE ) hdev = win32gui.RegisterDeviceNotification( hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE ) hdevs.append(hdev) # and create handles for all specified directories for d in dir_names: hdir = win32file.CreateFile( d, winnt.FILE_LIST_DIRECTORY, winnt.FILE_SHARE_READ | winnt.FILE_SHARE_WRITE | winnt.FILE_SHARE_DELETE, None, # security attributes win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED, # required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME. None, ) filter = win32gui_struct.PackDEV_BROADCAST_HANDLE(hdir) hdev = win32gui.RegisterDeviceNotification( hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE ) hdevs.append(hdev) # now start a message pump and wait for messages to be delivered. print("Watching", len(hdevs), "handles - press Ctrl+C to terminate, or") print("add and remove some USB devices...") if not dir_names: print("(Note you can also pass paths to watch on the command-line - eg,") print("pass the root of an inserted USB stick to see events specific to") print("that volume)") while 1: win32gui.PumpWaitingMessages() time.sleep(0.01) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(wc.lpszClassName, None)
null
171,494
import struct import pythoncom import pywintypes import win32api import win32con import win32file from win32com import storagecon stream_types = { win32con.BACKUP_DATA: "Standard data", win32con.BACKUP_EA_DATA: "Extended attribute data", win32con.BACKUP_SECURITY_DATA: "Security descriptor data", win32con.BACKUP_ALTERNATE_DATA: "Alternative data streams", win32con.BACKUP_LINK: "Hard link information", win32con.BACKUP_PROPERTY_DATA: "Property data", win32con.BACKUP_OBJECT_ID: "Objects identifiers", win32con.BACKUP_REPARSE_DATA: "Reparse points", win32con.BACKUP_SPARSE_BLOCK: "Sparse file", } print("Filename:", tempfile) win32_stream_id_format = "LLQL" while 1: bytes_read, win32_stream_id_buf, ctxt = win32file.BackupRead( h, win32_stream_id_size, win32_stream_id_buf, False, True, ctxt ) if bytes_read == 0: break ( ctxt, stream_type, stream_attributes, stream_size, stream_name_size, stream_name, ) = parse_stream_header(h, ctxt, win32_stream_id_buf[:]) if stream_size > 0: bytes_moved = win32file.BackupSeek(h, stream_size, ctxt) print("Moved: ", bytes_moved) win32file.BackupRead(h, win32_stream_id_size, win32_stream_id_buf, True, True, ctxt) win32file.CloseHandle(h) def parse_stream_header(h, ctxt, data): stream_type, stream_attributes, stream_size, stream_name_size = struct.unpack( win32_stream_id_format, data ) print( "\nType:", stream_type, stream_types[stream_type], "Attributes:", stream_attributes, "Size:", stream_size, "Name len:", stream_name_size, ) if stream_name_size > 0: ## ??? sdk says this size is in characters, but it appears to be number of bytes ??? bytes_read, stream_name_buf, ctxt = win32file.BackupRead( h, stream_name_size, None, False, True, ctxt ) stream_name = pywintypes.UnicodeFromRaw(stream_name_buf[:]) else: stream_name = "Unnamed" print("Name:" + stream_name) return ( ctxt, stream_type, stream_attributes, stream_size, stream_name_size, stream_name, )
null
171,495
import win32con from pywin32_testutil import str2bytes from win32clipboard import * def TestEmptyClipboard(): OpenClipboard() try: EmptyClipboard() assert ( EnumClipboardFormats(0) == 0 ), "Clipboard formats were available after emptying it!" finally: CloseClipboard()
null
171,496
import win32con from pywin32_testutil import str2bytes from win32clipboard import * def str2bytes(sval): def TestText(): OpenClipboard() try: text = "Hello from Python" text_bytes = str2bytes(text) SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) # CF_TEXT always gives us 'bytes' back . assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) finally: CloseClipboard() OpenClipboard() try: # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Unicode tests EmptyClipboard() text = "Hello from Python unicode" text_bytes = str2bytes(text) # Now set the Unicode value SetClipboardData(win32con.CF_UNICODETEXT, text) # Get it in Unicode. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) # Close and open the clipboard to ensure auto-conversions take place. finally: CloseClipboard() OpenClipboard() try: # Make sure I can still get the text as bytes got = GetClipboardData(win32con.CF_TEXT) assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) got = GetClipboardData(win32con.CF_OEMTEXT) assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) print("Clipboard text tests worked correctly") finally: CloseClipboard()
null
171,497
import win32con from pywin32_testutil import str2bytes from win32clipboard import * cf_names = {} def TestClipboardEnum(): OpenClipboard() try: # Enumerate over the clipboard types enum = 0 while 1: enum = EnumClipboardFormats(enum) if enum == 0: break assert IsClipboardFormatAvailable( enum ), "Have format, but clipboard says it is not available!" n = cf_names.get(enum, "") if not n: try: n = GetClipboardFormatName(enum) except error: n = "unknown (%s)" % (enum,) print("Have format", n) print("Clipboard enumerator tests worked correctly") finally: CloseClipboard()
null
171,498
import win32con from pywin32_testutil import str2bytes from win32clipboard import * class Foo: def __init__(self, **kw): def __cmp__(self, other): def __eq__(self, other): def TestCustomFormat(): OpenClipboard() try: # Just for the fun of it pickle Python objects through the clipboard fmt = RegisterClipboardFormat("Python Pickle Format") import pickle pickled_object = Foo(a=1, b=2, Hi=3) SetClipboardData(fmt, pickle.dumps(pickled_object)) # Now read it back. data = GetClipboardData(fmt) loaded_object = pickle.loads(data) assert pickle.loads(data) == pickled_object, "Didnt get the correct data!" print("Clipboard custom format tests worked correctly") finally: CloseClipboard()
null
171,499
import msvcrt import sys import threading import win32con from win32event import * from win32file import * def FindModem(): # Snoop over the comports, seeing if it is likely we have a modem. for i in range(1, 5): port = "COM%d" % (i,) try: handle = CreateFile( port, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, # exclusive access None, # no security win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None, ) # It appears that an available COM port will always success here, # just return 0 for the status flags. We only care that it has _any_ status # flags (and therefore probably a real modem) if GetCommModemStatus(handle) != 0: return port except error: pass # No port, or modem status failed. return None
null
171,500
import os import commctrl import win32api import win32con import win32gui import win32rcparser g_rcname = os.path.abspath( os.path.join(this_dir, "..", "test", "win32rcparser", "test.rc") ) class DemoWindow: def __init__(self, dlg_template): self.dlg_template = dlg_template def CreateWindow(self): self._DoCreate(win32gui.CreateDialogIndirect) def DoModal(self): return self._DoCreate(win32gui.DialogBoxIndirect) def _DoCreate(self, fn): message_map = { win32con.WM_INITDIALOG: self.OnInitDialog, win32con.WM_CLOSE: self.OnClose, win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, } return fn(0, self.dlg_template, 0, message_map) def OnInitDialog(self, hwnd, msg, wparam, lparam): self.hwnd = hwnd # centre the dialog desktop = win32gui.GetDesktopWindow() l, t, r, b = win32gui.GetWindowRect(self.hwnd) dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop) centre_x, centre_y = win32gui.ClientToScreen( desktop, ((dt_r - dt_l) // 2, (dt_b - dt_t) // 2) ) win32gui.MoveWindow( hwnd, centre_x - (r // 2), centre_y - (b // 2), r - l, b - t, 0 ) def OnCommand(self, hwnd, msg, wparam, lparam): # Needed to make OK/Cancel work - no other controls are handled. id = win32api.LOWORD(wparam) if id in [win32con.IDOK, win32con.IDCANCEL]: win32gui.EndDialog(hwnd, id) def OnClose(self, hwnd, msg, wparam, lparam): win32gui.EndDialog(hwnd, 0) def OnDestroy(self, hwnd, msg, wparam, lparam): pass def DemoModal(): # Load the .rc file. resources = win32rcparser.Parse(g_rcname) for id, ddef in resources.dialogs.items(): print("Displaying dialog", id) w = DemoWindow(ddef) w.DoModal()
null
171,501
import win32api import win32file print(fsrc, fdst) win32file.CopyFileEx( fsrc, fdst, ProgressRoutine, Data=operation_desc, Cancel=False, CopyFlags=win32file.COPY_FILE_RESTARTABLE, Transaction=None, ) def ProgressRoutine( TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile, Data, ): print(Data) print( TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile, ) ##if TotalBytesTransferred > 100000: ## return win32file.PROGRESS_STOP return win32file.PROGRESS_CONTINUE
null
171,502
import math import random import time import win32api import win32con import win32gui def _MyCallback(hwnd, extra): hwnds, classes = extra hwnds.append(hwnd) classes[win32gui.GetClassName(hwnd)] = 1 print("Enumerating all windows...") print("Testing drawing functions ...") print("All tests done!") def TestEnumWindows(): windows = [] classes = {} win32gui.EnumWindows(_MyCallback, (windows, classes)) print( "Enumerated a total of %d windows with %d classes" % (len(windows), len(classes)) ) if "tooltips_class32" not in classes: print("Hrmmmm - I'm very surprised to not find a 'tooltips_class32' class.")
null
171,503
import math import random import time import win32api import win32con import win32gui def OnPaint_1(hwnd, msg, wp, lp): dc, ps = win32gui.BeginPaint(hwnd) win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED) br = win32gui.CreateSolidBrush(win32api.RGB(255, 0, 0)) win32gui.SelectObject(dc, br) angle = win32gui.GetWindowLong(hwnd, win32con.GWL_USERDATA) win32gui.SetWindowLong(hwnd, win32con.GWL_USERDATA, angle + 2) r_angle = angle * (math.pi / 180) win32gui.SetWorldTransform( dc, { "M11": math.cos(r_angle), "M12": math.sin(r_angle), "M21": math.sin(r_angle) * -1, "M22": math.cos(r_angle), "Dx": 250, "Dy": 250, }, ) win32gui.MoveToEx(dc, 250, 250) win32gui.BeginPath(dc) win32gui.Pie(dc, 10, 70, 200, 200, 350, 350, 75, 10) win32gui.Chord(dc, 200, 200, 850, 0, 350, 350, 75, 10) win32gui.LineTo(dc, 300, 300) win32gui.LineTo(dc, 100, 20) win32gui.LineTo(dc, 20, 100) win32gui.LineTo(dc, 400, 0) win32gui.LineTo(dc, 0, 400) win32gui.EndPath(dc) win32gui.StrokeAndFillPath(dc) win32gui.EndPaint(hwnd, ps) return 0
null
171,504
import math import random import time import win32api import win32con import win32gui def OnPaint_2(hwnd, msg, wp, lp): dc, ps = win32gui.BeginPaint(hwnd) win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED) l, t, r, b = win32gui.GetClientRect(hwnd) for x in range(25): vertices = ( { "x": int(random.random() * r), "y": int(random.random() * b), "Red": int(random.random() * 0xFF00), "Green": 0, "Blue": 0, "Alpha": 0, }, { "x": int(random.random() * r), "y": int(random.random() * b), "Red": 0, "Green": int(random.random() * 0xFF00), "Blue": 0, "Alpha": 0, }, { "x": int(random.random() * r), "y": int(random.random() * b), "Red": 0, "Green": 0, "Blue": int(random.random() * 0xFF00), "Alpha": 0, }, ) mesh = ((0, 1, 2),) win32gui.GradientFill(dc, vertices, mesh, win32con.GRADIENT_FILL_TRIANGLE) win32gui.EndPaint(hwnd, ps) return 0
null
171,505
import math import random import time import win32api import win32con import win32gui wndproc_1 = {win32con.WM_PAINT: OnPaint_1} def TestSetWorldTransform(): wc = win32gui.WNDCLASS() wc.lpszClassName = "test_win32gui_1" wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpfnWndProc = wndproc_1 class_atom = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindow( wc.lpszClassName, "Spin the Lobster!", win32con.WS_CAPTION | win32con.WS_VISIBLE, 100, 100, 900, 900, 0, 0, 0, None, ) for x in range(500): win32gui.InvalidateRect(hwnd, None, True) win32gui.PumpWaitingMessages() time.sleep(0.01) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(wc.lpszClassName, None)
null
171,506
import math import random import time import win32api import win32con import win32gui wndproc_2 = {win32con.WM_PAINT: OnPaint_2} def TestGradientFill(): wc = win32gui.WNDCLASS() wc.lpszClassName = "test_win32gui_2" wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpfnWndProc = wndproc_2 class_atom = win32gui.RegisterClass(wc) hwnd = win32gui.CreateWindowEx( 0, class_atom, "Kaleidoscope", win32con.WS_CAPTION | win32con.WS_VISIBLE | win32con.WS_THICKFRAME | win32con.WS_SYSMENU, 100, 100, 900, 900, 0, 0, 0, None, ) s = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, s | win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(hwnd, 0, 175, win32con.LWA_ALPHA) for x in range(30): win32gui.InvalidateRect(hwnd, None, True) win32gui.PumpWaitingMessages() time.sleep(0.3) win32gui.DestroyWindow(hwnd) win32gui.UnregisterClass(class_atom, None)
null
171,507
import time import timer import win32event import win32gui class glork: def __init__(self, delay=1000, max=10): self.x = 0 self.max = max self.id = timer.set_timer(delay, self.increment) # Could use the threading module, but this is # a win32 extension test after all! :-) self.event = win32event.CreateEvent(None, 0, 0, None) def increment(self, id, time): print("x = %d" % self.x) self.x = self.x + 1 # if we've reached the max count, # kill off the timer. if self.x > self.max: # we could have used 'self.id' here, too timer.kill_timer(id) win32event.SetEvent(self.event) def demo(delay=1000, stop=10): g = glork(delay, stop) # Timers are message based - so we need # To run a message loop while waiting for our timers # to expire. start_time = time.time() while 1: # We can't simply give a timeout of 30 seconds, as # we may continouusly be recieving other input messages, # and therefore never expire. rc = win32event.MsgWaitForMultipleObjects( (g.event,), # list of objects 0, # wait all 500, # timeout win32event.QS_ALLEVENTS, # type of input ) if rc == win32event.WAIT_OBJECT_0: # Event signalled. break elif rc == win32event.WAIT_OBJECT_0 + 1: # Message waiting. if win32gui.PumpWaitingMessages(): raise RuntimeError("We got an unexpected WM_QUIT message!") else: # This wait timed-out. if time.time() - start_time > 30: raise RuntimeError("We timed out waiting for the timers to expire!")
null
171,508
import msvcrt import os import win32api import win32con import win32event import win32gui import win32process import win32security The provided code snippet includes necessary dependencies for implementing the `logonUser` function. Write a Python function `def logonUser(loginString)` to solve the following problem: Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password' Here is the function: def logonUser(loginString): """ Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password' """ domain, user, passwd = loginString.split("\n") return win32security.LogonUser( user, domain, passwd, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT, )
Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password'
171,509
import msvcrt import os import win32api import win32con import win32event import win32gui import win32process import win32security class Process: """ A Windows process. """ def __init__( self, cmd, login=None, hStdin=None, hStdout=None, hStderr=None, show=1, xy=None, xySize=None, desktop=None, ): """ Create a Windows process. cmd: command to run login: run as user 'Domain\nUser\nPassword' hStdin, hStdout, hStderr: handles for process I/O; default is caller's stdin, stdout & stderr show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...) xy: window offset (x, y) of upper left corner in pixels xySize: window size (width, height) in pixels desktop: lpDesktop - name of desktop e.g. 'winsta0\\default' None = inherit current desktop '' = create new desktop if necessary User calling login requires additional privileges: Act as part of the operating system [not needed on Windows XP] Increase quotas Replace a process level token Login string must EITHER be an administrator's account (ordinary user can't access current desktop - see Microsoft Q165194) OR use desktop='' to run another desktop invisibly (may be very slow to startup & finalize). """ si = win32process.STARTUPINFO() si.dwFlags = win32con.STARTF_USESTDHANDLES ^ win32con.STARTF_USESHOWWINDOW if hStdin is None: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdin if hStdout is None: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdout if hStderr is None: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStderr si.wShowWindow = show if xy is not None: si.dwX, si.dwY = xy si.dwFlags ^= win32con.STARTF_USEPOSITION if xySize is not None: si.dwXSize, si.dwYSize = xySize si.dwFlags ^= win32con.STARTF_USESIZE if desktop is not None: si.lpDesktop = desktop procArgs = ( None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32process.CREATE_NEW_CONSOLE, # dwCreationFlags None, # newEnvironment None, # currentDirectory si, ) # startupinfo if login is not None: hUser = logonUser(login) win32security.ImpersonateLoggedOnUser(hUser) procHandles = win32process.CreateProcessAsUser(hUser, *procArgs) win32security.RevertToSelf() else: procHandles = win32process.CreateProcess(*procArgs) self.hProcess, self.hThread, self.PId, self.TId = procHandles def wait(self, mSec=None): """ Wait for process to finish or for specified number of milliseconds to elapse. """ if mSec is None: mSec = win32event.INFINITE return win32event.WaitForSingleObject(self.hProcess, mSec) def kill(self, gracePeriod=5000): """ Kill process. Try for an orderly shutdown via WM_CLOSE. If still running after gracePeriod (5 sec. default), terminate. """ win32gui.EnumWindows(self.__close__, 0) if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0: win32process.TerminateProcess(self.hProcess, 0) win32api.Sleep(100) # wait for resources to be released def __close__(self, hwnd, dummy): """ EnumWindows callback - sends WM_CLOSE to any window owned by this process. """ TId, PId = win32process.GetWindowThreadProcessId(hwnd) if PId == self.PId: win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) def exitCode(self): """ Return process exit code. """ return win32process.GetExitCodeProcess(self.hProcess) The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw)` to solve the following problem: Run cmd as a child process and return exit code. mSec: terminate cmd after specified number of milliseconds stdin, stdout, stderr: file objects for child I/O (use hStdin etc. to attach handles instead of files); default is caller's stdin, stdout & stderr; kw: see Process.__init__ for more keyword options Here is the function: def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw): """ Run cmd as a child process and return exit code. mSec: terminate cmd after specified number of milliseconds stdin, stdout, stderr: file objects for child I/O (use hStdin etc. to attach handles instead of files); default is caller's stdin, stdout & stderr; kw: see Process.__init__ for more keyword options """ if stdin is not None: kw["hStdin"] = msvcrt.get_osfhandle(stdin.fileno()) if stdout is not None: kw["hStdout"] = msvcrt.get_osfhandle(stdout.fileno()) if stderr is not None: kw["hStderr"] = msvcrt.get_osfhandle(stderr.fileno()) child = Process(cmd, **kw) if child.wait(mSec) != win32event.WAIT_OBJECT_0: child.kill() raise WindowsError("process timeout exceeded") return child.exitCode()
Run cmd as a child process and return exit code. mSec: terminate cmd after specified number of milliseconds stdin, stdout, stderr: file objects for child I/O (use hStdin etc. to attach handles instead of files); default is caller's stdin, stdout & stderr; kw: see Process.__init__ for more keyword options
171,510
import sys import array import os import queue import struct import commctrl import win32api import win32con import win32gui_struct import winerror class DemoDialog(DemoWindowBase): def DoModal(self): def OnClose(self, hwnd, msg, wparam, lparam): def DemoModal(): w = DemoDialog() w.DoModal()
null
171,511
import sys import array import os import queue import struct import commctrl import win32api import win32con import win32gui_struct import winerror class DemoWindow(DemoWindowBase): def CreateWindow(self): # Create the window via CreateDialogBoxIndirect - it can then # work as a "normal" window, once a message loop is established. self._DoCreate(win32gui.CreateDialogIndirect) def OnClose(self, hwnd, msg, wparam, lparam): win32gui.DestroyWindow(hwnd) # We need to arrange to a WM_QUIT message to be sent to our # PumpMessages() loop. def OnDestroy(self, hwnd, msg, wparam, lparam): win32gui.PostQuitMessage(0) # Terminate the app. def DemoCreateWindow(): w = DemoWindow() w.CreateWindow() # PumpMessages runs until PostQuitMessage() is called by someone. win32gui.PumpMessages()
null
171,512
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DumpPythonRegistry(): try: h = wincerapi.CeRegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver, ) except win32api.error: print("The remote device does not appear to have Python installed") return 0 path, typ = wincerapi.CeRegQueryValueEx(h, None) print("The remote PythonPath is '%s'" % (str(path),)) h.Close() return 1
null
171,513
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DumpRegistry(root, level=0): # A recursive dump of the remote registry to test most functions. h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None) level_prefix = " " * level index = 0 # Enumerate values. while 1: try: name, data, typ = wincerapi.CeRegEnumValue(root, index) except win32api.error: break print("%s%s=%s" % (level_prefix, name, repr(str(data)))) index = index + 1 # Now enumerate all keys. index = 0 while 1: try: name, klass = wincerapi.CeRegEnumKeyEx(root, index) except win32api.error: break print("%s%s\\" % (level_prefix, name)) subkey = wincerapi.CeRegOpenKeyEx(root, name) DumpRegistry(subkey, level + 1) index = index + 1
null
171,514
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DemoCopyFile(): # Create a file on the device, and write a string. cefile = wincerapi.CeCreateFile( "TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None ) wincerapi.CeWriteFile(cefile, "Hello from Python") cefile.Close() # reopen the file and check the data. cefile = wincerapi.CeCreateFile( "TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None ) if wincerapi.CeReadFile(cefile, 100) != "Hello from Python": print("Couldnt read the data from the device!") cefile.Close() # Delete the test file wincerapi.CeDeleteFile("TestPython") print("Created, wrote to, read from and deleted a test file!")
null
171,515
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DemoCreateProcess(): try: hp, ht, pid, tid = wincerapi.CeCreateProcess( "Windows\\Python.exe", "", None, None, 0, 0, None, "", None ) # Not necessary, except to see if handle closing raises an exception # (if auto-closed, the error is suppressed) hp.Close() ht.Close() print("Python is running on the remote device!") except win32api.error as xxx_todo_changeme1: (hr, fn, msg) = xxx_todo_changeme1.args print("Couldnt execute remote process -", msg)
null
171,516
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DumpRemoteMachineStatus(): ( ACLineStatus, BatteryFlag, BatteryLifePercent, BatteryLifeTime, BatteryFullLifeTime, BackupBatteryFlag, BackupBatteryLifePercent, BackupBatteryLifeTime, BackupBatteryLifeTime, ) = wincerapi.CeGetSystemPowerStatusEx() if ACLineStatus: power = "AC" else: power = "battery" if BatteryLifePercent == 255: batPerc = "unknown" else: batPerc = BatteryLifePercent print( "The batteries are at %s%%, and is currently being powered by %s" % (batPerc, power) ) ( memLoad, totalPhys, availPhys, totalPage, availPage, totalVirt, availVirt, ) = wincerapi.CeGlobalMemoryStatus() print("The memory is %d%% utilized." % (memLoad)) print("%-20s%-10s%-10s" % ("", "Total", "Avail")) print("%-20s%-10s%-10s" % ("Physical Memory", totalPhys, availPhys)) print("%-20s%-10s%-10s" % ("Virtual Memory", totalVirt, availVirt)) print("%-20s%-10s%-10s" % ("Paging file", totalPage, availPage)) storeSize, freeSize = wincerapi.CeGetStoreInformation() print("%-20s%-10s%-10s" % ("File store", storeSize, freeSize)) print("The CE temp path is", wincerapi.CeGetTempPath()) print("The system info for the device is", wincerapi.CeGetSystemInfo())
null
171,517
import getopt import os import sys import win32api import win32con import win32event import wincerapi def DumpRemoteFolders(): # Dump all special folders possible. for name, val in list(wincerapi.__dict__.items()): if name[:6] == "CSIDL_": try: loc = str(wincerapi.CeGetSpecialFolderPath(val)) print("Folder %s is at %s" % (name, loc)) except win32api.error as details: pass # Get the shortcut targets for the "Start Menu" print("Dumping start menu shortcuts...") try: startMenu = str(wincerapi.CeGetSpecialFolderPath(wincerapi.CSIDL_STARTMENU)) except win32api.error as details: print("This device has no start menu!", details) startMenu = None if startMenu: for fileAttr in wincerapi.CeFindFiles(os.path.join(startMenu, "*")): fileName = fileAttr[8] fullPath = os.path.join(startMenu, str(fileName)) try: resolved = wincerapi.CeSHGetShortcutTarget(fullPath) except win32api.error as xxx_todo_changeme: (rc, fn, msg) = xxx_todo_changeme.args resolved = "#Error - %s" % msg print("%s->%s" % (fileName, resolved)) # print "The start menu is at", # print wincerapi.CeSHGetShortcutTarget("\\Windows\\Start Menu\\Shortcut to Python.exe.lnk")
null
171,518
import getopt import os import sys import win32api import win32con import win32event import wincerapi def usage(): print("Options:") print("-a - Execute all demos") print("-p - Execute Python process on remote device") print("-r - Dump the remote registry") print("-f - Dump all remote special folder locations") print("-s - Dont dump machine status") print("-y - Perform asynch init of CE connection")
null
171,519
import http.client import optparse import urllib.error import urllib.parse import urllib.request from base64 import decodestring, encodestring from sspi import ClientAuth options = None class ClientAuth(_BaseAuth): def __init__( self, pkg_name, # Name of the package to used. client_name=None, # User for whom credentials are used. auth_info=None, # or a tuple of (username, domain, password) targetspn=None, # Target security context provider name. scflags=None, # security context flags datarep=sspicon.SECURITY_NETWORK_DREP, ): def authorize(self, sec_buffer_in): def open_url(host, url): h = http.client.HTTPConnection(host) # h.set_debuglevel(9) h.putrequest("GET", url) h.endheaders() resp = h.getresponse() print("Initial response is", resp.status, resp.reason) body = resp.read() if resp.status == 302: # object moved url = "/" + resp.msg["location"] resp.close() h.putrequest("GET", url) h.endheaders() resp = h.getresponse() print("After redirect response is", resp.status, resp.reason) if options.show_headers: print("Initial response headers:") for name, val in list(resp.msg.items()): print(" %s: %s" % (name, val)) if options.show_body: print(body) if resp.status == 401: # 401: Unauthorized - here is where the real work starts auth_info = None if options.user or options.domain or options.password: auth_info = options.user, options.domain, options.password ca = ClientAuth("NTLM", auth_info=auth_info) auth_scheme = ca.pkg_info["Name"] data = None while 1: err, out_buf = ca.authorize(data) data = out_buf[0].Buffer # Encode it as base64 as required by HTTP auth = encodestring(data).replace("\012", "") h.putrequest("GET", url) h.putheader("Authorization", auth_scheme + " " + auth) h.putheader("Content-Length", "0") h.endheaders() resp = h.getresponse() if options.show_headers: print("Token dance headers:") for name, val in list(resp.msg.items()): print(" %s: %s" % (name, val)) if err == 0: break else: if resp.status != 401: print("Eeek - got response", resp.status) cl = resp.msg.get("content-length") if cl: print(repr(resp.read(int(cl)))) else: print("no content!") assert resp.status == 401, resp.status assert not resp.will_close, "NTLM is per-connection - must not close" schemes = [ s.strip() for s in resp.msg.get("WWW-Authenticate", "").split(",") ] for scheme in schemes: if scheme.startswith(auth_scheme): data = decodestring(scheme[len(auth_scheme) + 1 :]) break else: print( "Could not find scheme '%s' in schemes %r" % (auth_scheme, schemes) ) break resp.read() print("Final response status is", resp.status, resp.reason) if resp.status == 200: # Worked! # Check we can read it again without re-authenticating. if resp.will_close: print( "EEEK - response will close, but NTLM is per connection - it must stay open" ) body = resp.read() if options.show_body: print("Final response body:") print(body) h.putrequest("GET", url) h.endheaders() resp = h.getresponse() print("Second fetch response is", resp.status, resp.reason) if options.show_headers: print("Second response headers:") for name, val in list(resp.msg.items()): print(" %s: %s" % (name, val)) resp.read(int(resp.msg.get("content-length", 0))) elif resp.status == 500: print("Error text") print(resp.read()) else: if options.show_body: cl = resp.msg.get("content-length") print(resp.read(int(cl)))
null
171,520
import sys import win32security from sspi import ClientAuth, ServerAuth class ClientAuth(_BaseAuth): def __init__( self, pkg_name, # Name of the package to used. client_name=None, # User for whom credentials are used. auth_info=None, # or a tuple of (username, domain, password) targetspn=None, # Target security context provider name. scflags=None, # security context flags datarep=sspicon.SECURITY_NETWORK_DREP, ): def authorize(self, sec_buffer_in): class ServerAuth(_BaseAuth): def __init__( self, pkg_name, spn=None, scflags=None, datarep=sspicon.SECURITY_NETWORK_DREP ): def authorize(self, sec_buffer_in): def validate(username, password, domain=""): auth_info = username, domain, password ca = ClientAuth("NTLM", auth_info=auth_info) sa = ServerAuth("NTLM") data = err = None while err != 0: err, data = ca.authorize(data) err, data = sa.authorize(data) # If we get here without exception, we worked!
null
171,521
import sspi import sspicon import win32api import win32security def lookup_ret_code(err): for k, v in list(sspicon.__dict__.items()): if k[0:6] in ("SEC_I_", "SEC_E_") and v == err: return k
null
171,522
import http.client import optparse import socketserver import struct import traceback import sspi import win32api import win32security def GetUserName(): try: return win32api.GetUserName() except win32api.error as details: # Seeing 'access denied' errors here for non-local users (presumably # without permission to login locally). Get the fully-qualified # username, although a side-effect of these permission-denied errors # is a lack of Python codecs - so printing the Unicode value fails. # So just return the repr(), and avoid codecs completely. return repr(win32api.GetUserNameEx(win32api.NameSamCompatible))
null
171,523
import http.client import optparse import socketserver import struct import traceback import sspi import win32api import win32security options = None class SSPISocketServer(socketserver.TCPServer): def __init__(self, *args, **kw): socketserver.TCPServer.__init__(self, *args, **kw) self.sa = sspi.ServerAuth(options.package) def verify_request(self, sock, ca): # Do the sspi auth dance self.sa.reset() while 1: data = _get_msg(sock) if data is None: return False try: err, sec_buffer = self.sa.authorize(data) except sspi.error as details: print("FAILED to authorize client:", details) return False if err == 0: break _send_msg(sock, sec_buffer[0].Buffer) return True def process_request(self, request, client_address): # An example using the connection once it is established. print("The server is running as user", GetUserName()) self.sa.ctxt.ImpersonateSecurityContext() try: print("Having conversation with client as user", GetUserName()) while 1: # we need to grab 2 bits of data - the encrypted data, and the # 'key' data = _get_msg(request) key = _get_msg(request) if data is None or key is None: break data = self.sa.decrypt(data, key) print("Client sent:", repr(data)) finally: self.sa.ctxt.RevertSecurityContext() self.close_request(request) print("The server is back to user", GetUserName()) def serve(): s = SSPISocketServer(("localhost", options.port), None) print("Running test server...") s.serve_forever()
null
171,524
import http.client import optparse import socketserver import struct import traceback import sspi import win32api import win32security options = None def _send_msg(s, m): s.send(struct.pack("i", len(m))) s.send(m) def _get_msg(s): size_data = s.recv(struct.calcsize("i")) if not size_data: return None cb = struct.unpack("i", size_data)[0] return s.recv(cb) def sspi_client(): c = http.client.HTTPConnection("localhost", options.port) c.connect() # Do the auth dance. ca = sspi.ClientAuth(options.package, targetspn=options.target_spn) data = None while 1: err, out_buf = ca.authorize(data) _send_msg(c.sock, out_buf[0].Buffer) if err == 0: break data = _get_msg(c.sock) print("Auth dance complete - sending a few encryted messages") # Assume out data is sensitive - encrypt the message. for data in "Hello from the client".split(): blob, key = ca.encrypt(data) _send_msg(c.sock, blob) _send_msg(c.sock, key) c.sock.close() print("Client completed.")
null
171,525
import pywintypes import win32api import win32con import win32security import winerror from security_enums import ( SECURITY_IMPERSONATION_LEVEL, TOKEN_ELEVATION_TYPE, TOKEN_GROUP_ATTRIBUTES, TOKEN_PRIVILEGE_ATTRIBUTES, TOKEN_TYPE, ) lt = dump_token(th) if lt: print("\n\nlinked token info:") dump_token(lt) TOKEN_TYPE = Enum("TokenPrimary", "TokenImpersonation") TOKEN_ELEVATION_TYPE = Enum( "TokenElevationTypeDefault", "TokenElevationTypeFull", "TokenElevationTypeLimited" ) SECURITY_IMPERSONATION_LEVEL = Enum( "SecurityAnonymous", "SecurityIdentification", "SecurityImpersonation", "SecurityDelegation", ) TOKEN_GROUP_ATTRIBUTES = Enum( "SE_GROUP_MANDATORY", "SE_GROUP_ENABLED_BY_DEFAULT", "SE_GROUP_ENABLED", "SE_GROUP_OWNER", "SE_GROUP_USE_FOR_DENY_ONLY", "SE_GROUP_INTEGRITY", "SE_GROUP_INTEGRITY_ENABLED", "SE_GROUP_LOGON_ID", "SE_GROUP_RESOURCE", ) TOKEN_PRIVILEGE_ATTRIBUTES = Enum( "SE_PRIVILEGE_ENABLED_BY_DEFAULT", "SE_PRIVILEGE_ENABLED", "SE_PRIVILEGE_REMOVED", "SE_PRIVILEGE_USED_FOR_ACCESS", ) def dump_token(th): token_type = win32security.GetTokenInformation(th, win32security.TokenType) print("TokenType:", token_type, TOKEN_TYPE.lookup_name(token_type)) if token_type == win32security.TokenImpersonation: imp_lvl = win32security.GetTokenInformation( th, win32security.TokenImpersonationLevel ) print( "TokenImpersonationLevel:", imp_lvl, SECURITY_IMPERSONATION_LEVEL.lookup_name(imp_lvl), ) print( "TokenSessionId:", win32security.GetTokenInformation(th, win32security.TokenSessionId), ) privs = win32security.GetTokenInformation(th, win32security.TokenPrivileges) print("TokenPrivileges:") for priv_luid, priv_flags in privs: flag_names, unk = TOKEN_PRIVILEGE_ATTRIBUTES.lookup_flags(priv_flags) flag_desc = " ".join(flag_names) if unk: flag_desc += "(" + str(unk) + ")" priv_name = win32security.LookupPrivilegeName("", priv_luid) priv_desc = win32security.LookupPrivilegeDisplayName("", priv_name) print("\t", priv_name, priv_desc, priv_flags, flag_desc) print("TokenGroups:") groups = win32security.GetTokenInformation(th, win32security.TokenGroups) for group_sid, group_attr in groups: flag_names, unk = TOKEN_GROUP_ATTRIBUTES.lookup_flags(group_attr) flag_desc = " ".join(flag_names) if unk: flag_desc += "(" + str(unk) + ")" if group_attr & TOKEN_GROUP_ATTRIBUTES.SE_GROUP_LOGON_ID: sid_desc = "Logon sid" else: sid_desc = win32security.LookupAccountSid("", group_sid) print("\t", group_sid, sid_desc, group_attr, flag_desc) ## Vista token information types, will throw (87, 'GetTokenInformation', 'The parameter is incorrect.') on earier OS try: is_elevated = win32security.GetTokenInformation( th, win32security.TokenElevation ) print("TokenElevation:", is_elevated) except pywintypes.error as details: if details.winerror != winerror.ERROR_INVALID_PARAMETER: raise return None print( "TokenHasRestrictions:", win32security.GetTokenInformation(th, win32security.TokenHasRestrictions), ) print( "TokenMandatoryPolicy", win32security.GetTokenInformation(th, win32security.TokenMandatoryPolicy), ) print( "TokenVirtualizationAllowed:", win32security.GetTokenInformation(th, win32security.TokenVirtualizationAllowed), ) print( "TokenVirtualizationEnabled:", win32security.GetTokenInformation(th, win32security.TokenVirtualizationEnabled), ) elevation_type = win32security.GetTokenInformation( th, win32security.TokenElevationType ) print( "TokenElevationType:", elevation_type, TOKEN_ELEVATION_TYPE.lookup_name(elevation_type), ) if elevation_type != win32security.TokenElevationTypeDefault: lt = win32security.GetTokenInformation(th, win32security.TokenLinkedToken) print("TokenLinkedToken:", lt) else: lt = None return lt
null
171,526
import sys import pywintypes from ntsecuritycon import * from win32net import NetUserModalsGet from win32security import LookupAccountSid def LookupAliasFromRid(TargetComputer, Rid): # Sid is the same regardless of machine, since the well-known # BUILTIN domain is referenced. sid = pywintypes.SID() sid.Initialize(SECURITY_NT_AUTHORITY, 2) for i, r in enumerate((SECURITY_BUILTIN_DOMAIN_RID, Rid)): sid.SetSubAuthority(i, r) name, domain, typ = LookupAccountSid(TargetComputer, sid) return name
null
171,527
import sys import pywintypes from ntsecuritycon import * from win32net import NetUserModalsGet from win32security import LookupAccountSid def LookupUserGroupFromRid(TargetComputer, Rid): # get the account domain Sid on the target machine # note: if you were looking up multiple sids based on the same # account domain, only need to call this once. umi2 = NetUserModalsGet(TargetComputer, 2) domain_sid = umi2["domain_id"] SubAuthorityCount = domain_sid.GetSubAuthorityCount() # create and init new sid with acct domain Sid + acct Rid sid = pywintypes.SID() sid.Initialize(domain_sid.GetSidIdentifierAuthority(), SubAuthorityCount + 1) # copy existing subauthorities from account domain Sid into # new Sid for i in range(SubAuthorityCount): sid.SetSubAuthority(i, domain_sid.GetSubAuthority(i)) # append Rid to new Sid sid.SetSubAuthority(SubAuthorityCount, Rid) name, domain, typ = LookupAccountSid(TargetComputer, sid) return name
null
171,528
import win32api import win32security import winerror from ntsecuritycon import * def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error as details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token, since no thread token # exists tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(), TOKEN_QUERY) sid, attr = win32security.GetTokenInformation(tok, TokenUser) win32api.CloseHandle(tok) name, dom, typ = win32security.LookupAccountSid(None, sid) return dom
null
171,529
import os import win32api import win32file import winerror f = open(fname, "w") f.write("xxxxxxxxxxxxxxxx\n" * 32768) f.close() f = open(fname + ":stream_y", "w") f.write("yyyyyyyyyyyyyyyy\n" * 32768) f.close() f = open(fname + ":stream_z", "w") f.write("zzzzzzzzzzzzzzzz\n" * 32768) f.close() f = open(bkup_fname, "wb") f = open(bkup_fname, "rb") def ReadCallback(input_buffer, data, buflen): fnamein, fnameout, f = data ## print fnamein, fnameout, buflen f.write(input_buffer) ## python 2.3 throws an error if return value is a plain int return winerror.ERROR_SUCCESS
null
171,530
import os import win32api import win32file import winerror f = open(fname, "w") f.write("xxxxxxxxxxxxxxxx\n" * 32768) f.close() f = open(fname + ":stream_y", "w") f.write("yyyyyyyyyyyyyyyy\n" * 32768) f.close() f = open(fname + ":stream_z", "w") f.write("zzzzzzzzzzzzzzzz\n" * 32768) f.close() f = open(bkup_fname, "wb") f = open(bkup_fname, "rb") def WriteCallback(output_buffer, data, buflen): fnamebackup, fnameout, f = data file_data = f.read(buflen) ## returning 0 as len terminates WriteEncryptedFileRaw output_len = len(file_data) output_buffer[:output_len] = file_data return winerror.ERROR_SUCCESS, output_len
null
171,531
import _thread import traceback import pywintypes import servicemanager import win32con import win32service import win32serviceutil import winerror from ntsecuritycon import * from win32api import * from win32event import * from win32file import * from win32pipe import * def ApplyIgnoreError(fn, args): try: return fn(*args) except error: # Ignore win32api errors. return None
null
171,532
import os import sys import traceback import pywintypes import win32api import winerror from win32event import * from win32file import * from win32pipe import * verbose = 0 def CallPipe(fn, args): ret = None retryCount = 0 while retryCount < 8: # Keep looping until user cancels. retryCount = retryCount + 1 try: return fn(*args) except win32api.error as exc: if exc.winerror == winerror.ERROR_PIPE_BUSY: win32api.Sleep(5000) continue else: raise raise RuntimeError("Could not make a connection to the server") def testClient(server, msg): if verbose: print("Sending", msg) data = CallPipe( CallNamedPipe, ("\\\\%s\\pipe\\PyPipeTest" % server, msg, 256, NMPWAIT_WAIT_FOREVER), ) if verbose: print("Server sent back '%s'" % data) print("Sent and received a message!")
null
171,533
import os import sys import traceback import pywintypes import win32api import winerror from win32event import * from win32file import * from win32pipe import * verbose = 0 def CallPipe(fn, args): def testLargeMessage(server, size=4096): if verbose: print("Sending message of size %d" % (size)) msg = "*" * size data = CallPipe( CallNamedPipe, ("\\\\%s\\pipe\\PyPipeTest" % server, msg, 512, NMPWAIT_WAIT_FOREVER), ) if len(data) - size: print("Sizes are all wrong - send %d, got back %d" % (size, len(data)))
null
171,534
import os import sys import traceback import pywintypes import win32api import winerror from win32event import * from win32file import * from win32pipe import * def stressThread(server, numMessages, wait): def stressTestClient(server, numThreads, numMessages): import _thread thread_waits = [] for t_num in range(numThreads): # Note I could just wait on thread handles (after calling DuplicateHandle) # See the service itself for an example of waiting for the clients... wait = CreateEvent(None, 0, 0, None) thread_waits.append(wait) _thread.start_new_thread(stressThread, (server, numMessages, wait)) # Wait for all threads to finish. WaitForMultipleObjects(thread_waits, 1, INFINITE)
null
171,535
import win32con import win32service def EnumServices(): resume = 0 accessSCM = win32con.GENERIC_READ accessSrv = win32service.SC_MANAGER_ALL_ACCESS # Open Service Control Manager hscm = win32service.OpenSCManager(None, None, accessSCM) # Enumerate Service Control Manager DB typeFilter = win32service.SERVICE_WIN32 stateFilter = win32service.SERVICE_STATE_ALL statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter) for short_name, desc, status in statuses: print(short_name, desc, status)
null
171,536
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None The provided code snippet includes necessary dependencies for implementing the `CreateUser` function. Write a Python function `def CreateUser()` to solve the following problem: Creates a new test user, then deletes the user Here is the function: def CreateUser(): "Creates a new test user, then deletes the user" testName = "PyNetTestUser" try: win32net.NetUserDel(server, testName) print("Warning - deleted user before creating it!") except win32net.error: pass d = {} d["name"] = testName d["password"] = "deleteme" d["priv"] = win32netcon.USER_PRIV_USER d["comment"] = "Delete me - created by Python test code" d["flags"] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT win32net.NetUserAdd(server, 1, d) try: try: win32net.NetUserChangePassword(server, testName, "wrong", "new") print("ERROR: NetUserChangePassword worked with a wrong password!") except win32net.error: pass win32net.NetUserChangePassword(server, testName, "deleteme", "new") finally: win32net.NetUserDel(server, testName) print("Created a user, changed their password, and deleted them!")
Creates a new test user, then deletes the user
171,537
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None def verbose(msg): if verbose_level: print(msg) The provided code snippet includes necessary dependencies for implementing the `UserEnum` function. Write a Python function `def UserEnum()` to solve the following problem: Enumerates all the local users Here is the function: def UserEnum(): "Enumerates all the local users" resume = 0 nuser = 0 while 1: data, total, resume = win32net.NetUserEnum( server, 3, win32netcon.FILTER_NORMAL_ACCOUNT, resume ) verbose( "Call to NetUserEnum obtained %d entries of %d total" % (len(data), total) ) for user in data: verbose("Found user %s" % user["name"]) nuser = nuser + 1 if not resume: break assert nuser, "Could not find any users!" print("Enumerated all the local users")
Enumerates all the local users
171,538
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None def verbose(msg): if verbose_level: print(msg) The provided code snippet includes necessary dependencies for implementing the `GroupEnum` function. Write a Python function `def GroupEnum()` to solve the following problem: Enumerates all the domain groups Here is the function: def GroupEnum(): "Enumerates all the domain groups" nmembers = 0 resume = 0 while 1: data, total, resume = win32net.NetGroupEnum(server, 1, resume) # print "Call to NetGroupEnum obtained %d entries of %d total" % (len(data), total) for group in data: verbose("Found group %(name)s:%(comment)s " % group) memberresume = 0 while 1: memberdata, total, memberresume = win32net.NetGroupGetUsers( server, group["name"], 0, resume ) for member in memberdata: verbose(" Member %(name)s" % member) nmembers = nmembers + 1 if memberresume == 0: break if not resume: break assert nmembers, "Couldnt find a single member in a single group!" print("Enumerated all the groups")
Enumerates all the domain groups
171,539
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None def verbose(msg): if verbose_level: print(msg) The provided code snippet includes necessary dependencies for implementing the `LocalGroupEnum` function. Write a Python function `def LocalGroupEnum()` to solve the following problem: Enumerates all the local groups Here is the function: def LocalGroupEnum(): "Enumerates all the local groups" resume = 0 nmembers = 0 while 1: data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume) for group in data: verbose("Found group %(name)s:%(comment)s " % group) memberresume = 0 while 1: memberdata, total, memberresume = win32net.NetLocalGroupGetMembers( server, group["name"], 2, resume ) for member in memberdata: # Just for the sake of it, we convert the SID to a username username, domain, type = win32security.LookupAccountSid( server, member["sid"] ) nmembers = nmembers + 1 verbose(" Member %s (%s)" % (username, member["domainandname"])) if memberresume == 0: break if not resume: break assert nmembers, "Couldnt find a single member in a single group!" print("Enumerated all the local groups")
Enumerates all the local groups
171,540
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None def verbose(msg): if verbose_level: print(msg) The provided code snippet includes necessary dependencies for implementing the `ServerEnum` function. Write a Python function `def ServerEnum()` to solve the following problem: Enumerates all servers on the network Here is the function: def ServerEnum(): "Enumerates all servers on the network" resume = 0 while 1: data, total, resume = win32net.NetServerEnum( server, 100, win32netcon.SV_TYPE_ALL, None, resume ) for s in data: verbose("Found server %s" % s["name"]) # Now loop over the shares. shareresume = 0 while 1: sharedata, total, shareresume = win32net.NetShareEnum( server, 2, shareresume ) for share in sharedata: verbose( " %(netname)s (%(path)s):%(remark)s - in use by %(current_uses)d users" % share ) if not shareresume: break if not resume: break print("Enumerated all the servers on the network")
Enumerates all servers on the network
171,541
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None The provided code snippet includes necessary dependencies for implementing the `LocalGroup` function. Write a Python function `def LocalGroup(uname=None)` to solve the following problem: Creates a local group, adds some members, deletes them, then removes the group Here is the function: def LocalGroup(uname=None): "Creates a local group, adds some members, deletes them, then removes the group" level = 3 if uname is None: uname = win32api.GetUserName() if uname.find("\\") < 0: uname = win32api.GetDomainName() + "\\" + uname group = "python_test_group" # delete the group if it already exists try: win32net.NetLocalGroupDel(server, group) print("WARNING: existing local group '%s' has been deleted.") except win32net.error: pass group_data = {"name": group} win32net.NetLocalGroupAdd(server, 1, group_data) try: u = {"domainandname": uname} win32net.NetLocalGroupAddMembers(server, group, level, [u]) mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print("members are", mem) if mem[0]["domainandname"] != uname: print("ERROR: LocalGroup just added %s, but members are %r" % (uname, mem)) # Convert the list of dicts to a list of strings. win32net.NetLocalGroupDelMembers( server, group, [m["domainandname"] for m in mem] ) finally: win32net.NetLocalGroupDel(server, group) print("Created a local group, added and removed members, then deleted the group")
Creates a local group, adds some members, deletes them, then removes the group
171,542
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None def verbose(msg): if verbose_level: print(msg) The provided code snippet includes necessary dependencies for implementing the `GetInfo` function. Write a Python function `def GetInfo(userName=None)` to solve the following problem: Dumps level 3 information about the current user Here is the function: def GetInfo(userName=None): "Dumps level 3 information about the current user" if userName is None: userName = win32api.GetUserName() print("Dumping level 3 information about user") info = win32net.NetUserGetInfo(server, userName, 3) for key, val in list(info.items()): verbose("%s=%s" % (key, val))
Dumps level 3 information about the current user
171,543
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security server = None The provided code snippet includes necessary dependencies for implementing the `SetInfo` function. Write a Python function `def SetInfo(userName=None)` to solve the following problem: Attempts to change the current users comment, then set it back Here is the function: def SetInfo(userName=None): "Attempts to change the current users comment, then set it back" if userName is None: userName = win32api.GetUserName() oldData = win32net.NetUserGetInfo(server, userName, 3) try: d = oldData.copy() d["usr_comment"] = "Test comment" win32net.NetUserSetInfo(server, userName, 3, d) new = win32net.NetUserGetInfo(server, userName, 3)["usr_comment"] if str(new) != "Test comment": raise RuntimeError("Could not read the same comment back - got %s" % new) print("Changed the data for the user") finally: win32net.NetUserSetInfo(server, userName, 3, oldData)
Attempts to change the current users comment, then set it back
171,544
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security The provided code snippet includes necessary dependencies for implementing the `SetComputerInfo` function. Write a Python function `def SetComputerInfo()` to solve the following problem: Doesnt actually change anything, just make sure we could ;-) Here is the function: def SetComputerInfo(): "Doesnt actually change anything, just make sure we could ;-)" info = win32net.NetWkstaGetInfo(None, 502) # *sob* - but we can't! Why not!!! # win32net.NetWkstaSetInfo(None, 502, info)
Doesnt actually change anything, just make sure we could ;-)
171,545
import getopt import sys import traceback import win32api import win32net import win32netcon import win32security def usage(tests): import os print("Usage: %s [-s server ] [-v] [Test ...]" % os.path.basename(sys.argv[0])) print(" -v : Verbose - print more information") print(" -s : server - execute the tests against the named server") print(" -c : include the CreateUser test by default") print("where Test is one of:") for t in tests: print(t.__name__, ":", t.__doc__) print() print("If not tests are specified, all tests are run") sys.exit(1)
null
171,546
import os import win32api import win32con import win32file def SimpleFileDemo(): testName = os.path.join(win32api.GetTempPath(), "win32file_demo_test_file") if os.path.exists(testName): os.unlink(testName) # Open the file for writing. handle = win32file.CreateFile( testName, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None ) test_data = "Hello\0there".encode("ascii") win32file.WriteFile(handle, test_data) handle.Close() # Open it for reading. handle = win32file.CreateFile( testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None ) rc, data = win32file.ReadFile(handle, 1024) handle.Close() if data == test_data: print("Successfully wrote and read a file") else: raise Exception("Got different data back???") os.unlink(testName)
null
171,547
import win32evtlog def c(reason, context, evt): if reason == win32evtlog.EvtSubscribeActionError: print("EvtSubscribeActionError") elif reason == win32evtlog.EvtSubscribeActionDeliver: print("EvtSubscribeActionDeliver") else: print("??? Unknown action ???", reason) context.append(win32evtlog.EvtRender(evt, win32evtlog.EvtRenderEventXml)) return 0
null
171,548
import os import struct import win32api import win32con import win32file import win32transaction import winerror import winioctlcon from pywin32_testutil import str2bytes def str2bytes(sval): if sys.version_info < (3, 0) and isinstance(sval, str): sval = sval.decode("latin1") return sval.encode("latin1") The provided code snippet includes necessary dependencies for implementing the `demo` function. Write a Python function `def demo()` to solve the following problem: Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION: typedef struct _TXFS_CREATE_MINIVERSION_INFO{ USHORT StructureVersion; USHORT StructureLength; ULONG BaseVersion; USHORT MiniVersion;} Here is the function: def demo(): """ Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION: typedef struct _TXFS_CREATE_MINIVERSION_INFO{ USHORT StructureVersion; USHORT StructureLength; ULONG BaseVersion; USHORT MiniVersion;} """ buf_fmt = "HHLH0L" ## buffer size must include struct padding buf_size = struct.calcsize(buf_fmt) tempdir = win32api.GetTempPath() tempfile = win32api.GetTempFileName(tempdir, "cft")[0] print("Demonstrating transactions on tempfile", tempfile) f = open(tempfile, "w") f.write("This is original file.\n") f.close() trans = win32transaction.CreateTransaction( Description="Test creating miniversions of a file" ) hfile = win32file.CreateFileW( tempfile, win32con.GENERIC_READ | win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, ) win32file.WriteFile(hfile, str2bytes("This is first miniversion.\n")) buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf) win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN) win32file.WriteFile(hfile, str2bytes("This is second miniversion!\n")) buf = win32file.DeviceIoControl( hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION, None, buf_size, None ) struct_ver, struct_len, base_ver, ver_2 = struct.unpack(buf_fmt, buf) hfile.Close() ## miniversions can't be opened with write access hfile_0 = win32file.CreateFileW( tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=base_ver, ) print("version:", base_ver, win32file.ReadFile(hfile_0, 100)) hfile_0.Close() hfile_1 = win32file.CreateFileW( tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=ver_1, ) print("version:", ver_1, win32file.ReadFile(hfile_1, 100)) hfile_1.Close() hfile_2 = win32file.CreateFileW( tempfile, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None, Transaction=trans, MiniVersion=ver_2, ) print("version:", ver_2, win32file.ReadFile(hfile_2, 100)) hfile_2.Close() ## MiniVersions are destroyed when transaction is committed or rolled back win32transaction.CommitTransaction(trans) os.unlink(tempfile)
Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION: typedef struct _TXFS_CREATE_MINIVERSION_INFO{ USHORT StructureVersion; USHORT StructureLength; ULONG BaseVersion; USHORT MiniVersion;}
171,549
def MEVT_EVENTTYPE(x): return (BYTE)(((x) >> 24) & 0xFF)
null
171,550
def MEVT_EVENTPARM(x): return (DWORD)((x) & 0x00FFFFFF)
null
171,551
def MCI_MSF_MINUTE(msf): return (BYTE)(msf)
null