id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
177,874
import enum import dis import opcode as _opcode import sys from marshal import dumps as _dumps from _pydevd_frame_eval.vendored import bytecode as _bytecode def const_key(obj): try: return _dumps(obj) except ValueError: # For other types, we use the object identifier as an unique identifier # to ensure that they are seen as unequal. return (type(obj), id(obj))
null
177,875
import enum import dis import opcode as _opcode import sys from marshal import dumps as _dumps from _pydevd_frame_eval.vendored import bytecode as _bytecode def _pushes_back(opname): if opname in ["CALL_FINALLY"]: # CALL_FINALLY pushes the address of the "finally" block instead of a # value, hence we don't treat it as pushing back op return False return ( opname.startswith("UNARY_") or opname.startswith("GET_") # BUILD_XXX_UNPACK have been removed in 3.9 or opname.startswith("BINARY_") or opname.startswith("INPLACE_") or opname.startswith("BUILD_") or opname.startswith("CALL_") ) or opname in ( "LIST_TO_TUPLE", "LIST_EXTEND", "SET_UPDATE", "DICT_UPDATE", "DICT_MERGE", "IS_OP", "CONTAINS_OP", "FORMAT_VALUE", "MAKE_FUNCTION", "IMPORT_NAME", # technically, these three do not push back, but leave the container # object on TOS "SET_ADD", "LIST_APPEND", "MAP_ADD", "LOAD_ATTR", )
null
177,876
import enum import dis import opcode as _opcode import sys from marshal import dumps as _dumps from _pydevd_frame_eval.vendored import bytecode as _bytecode def _check_lineno(lineno): if not isinstance(lineno, int): raise TypeError("lineno must be an int") if lineno < 1: raise ValueError("invalid lineno")
null
177,877
import enum import dis import opcode as _opcode import sys from marshal import dumps as _dumps from _pydevd_frame_eval.vendored import bytecode as _bytecode def _check_arg_int(name, arg): if not isinstance(arg, int): raise TypeError( "operation %s argument must be an int, " "got %s" % (name, type(arg).__name__) ) if not (0 <= arg <= 2147483647): raise ValueError( "operation %s argument must be in " "the range 0..2,147,483,647" % name )
null
177,878
import sys from enum import IntFlag from _pydevd_frame_eval.vendored import bytecode as _bytecode class CompilerFlags(IntFlag): """Possible values of the co_flags attribute of Code object. Note: We do not rely on inspect values here as some of them are missing and furthermore would be version dependent. """ OPTIMIZED = 0x00001 # noqa NEWLOCALS = 0x00002 # noqa VARARGS = 0x00004 # noqa VARKEYWORDS = 0x00008 # noqa NESTED = 0x00010 # noqa GENERATOR = 0x00020 # noqa NOFREE = 0x00040 # noqa # New in Python 3.5 # Used for coroutines defined using async def ie native coroutine COROUTINE = 0x00080 # noqa # Used for coroutines defined as a generator and then decorated using # types.coroutine ITERABLE_COROUTINE = 0x00100 # noqa # New in Python 3.6 # Generator defined in an async def function ASYNC_GENERATOR = 0x00200 # noqa # __future__ flags # future flags changed in Python 3.9 if sys.version_info < (3, 9): FUTURE_GENERATOR_STOP = 0x80000 # noqa if sys.version_info > (3, 6): FUTURE_ANNOTATIONS = 0x100000 else: FUTURE_GENERATOR_STOP = 0x800000 # noqa FUTURE_ANNOTATIONS = 0x1000000 The provided code snippet includes necessary dependencies for implementing the `infer_flags` function. Write a Python function `def infer_flags(bytecode, is_async=None)` to solve the following problem: Infer the proper flags for a bytecode based on the instructions. Because the bytecode does not have enough context to guess if a function is asynchronous the algorithm tries to be conservative and will never turn a previously async code into a sync one. Parameters ---------- bytecode : Bytecode | ConcreteBytecode | ControlFlowGraph Bytecode for which to infer the proper flags is_async : bool | None, optional Force the code to be marked as asynchronous if True, prevent it from being marked as asynchronous if False and simply infer the best solution based on the opcode and the existing flag if None. Here is the function: def infer_flags(bytecode, is_async=None): """Infer the proper flags for a bytecode based on the instructions. Because the bytecode does not have enough context to guess if a function is asynchronous the algorithm tries to be conservative and will never turn a previously async code into a sync one. Parameters ---------- bytecode : Bytecode | ConcreteBytecode | ControlFlowGraph Bytecode for which to infer the proper flags is_async : bool | None, optional Force the code to be marked as asynchronous if True, prevent it from being marked as asynchronous if False and simply infer the best solution based on the opcode and the existing flag if None. """ flags = CompilerFlags(0) if not isinstance( bytecode, (_bytecode.Bytecode, _bytecode.ConcreteBytecode, _bytecode.ControlFlowGraph), ): msg = ( "Expected a Bytecode, ConcreteBytecode or ControlFlowGraph " "instance not %s" ) raise ValueError(msg % bytecode) instructions = ( bytecode.get_instructions() if isinstance(bytecode, _bytecode.ControlFlowGraph) else bytecode ) instr_names = { i.name for i in instructions if not isinstance(i, (_bytecode.SetLineno, _bytecode.Label)) } # Identify optimized code if not (instr_names & {"STORE_NAME", "LOAD_NAME", "DELETE_NAME"}): flags |= CompilerFlags.OPTIMIZED # Check for free variables if not ( instr_names & { "LOAD_CLOSURE", "LOAD_DEREF", "STORE_DEREF", "DELETE_DEREF", "LOAD_CLASSDEREF", } ): flags |= CompilerFlags.NOFREE # Copy flags for which we cannot infer the right value flags |= bytecode.flags & ( CompilerFlags.NEWLOCALS | CompilerFlags.VARARGS | CompilerFlags.VARKEYWORDS | CompilerFlags.NESTED ) sure_generator = instr_names & {"YIELD_VALUE"} maybe_generator = instr_names & {"YIELD_VALUE", "YIELD_FROM"} sure_async = instr_names & { "GET_AWAITABLE", "GET_AITER", "GET_ANEXT", "BEFORE_ASYNC_WITH", "SETUP_ASYNC_WITH", "END_ASYNC_FOR", } # If performing inference or forcing an async behavior, first inspect # the flags since this is the only way to identify iterable coroutines if is_async in (None, True): if bytecode.flags & CompilerFlags.COROUTINE: if sure_generator: flags |= CompilerFlags.ASYNC_GENERATOR else: flags |= CompilerFlags.COROUTINE elif bytecode.flags & CompilerFlags.ITERABLE_COROUTINE: if sure_async: msg = ( "The ITERABLE_COROUTINE flag is set but bytecode that" "can only be used in async functions have been " "detected. Please unset that flag before performing " "inference." ) raise ValueError(msg) flags |= CompilerFlags.ITERABLE_COROUTINE elif bytecode.flags & CompilerFlags.ASYNC_GENERATOR: if not sure_generator: flags |= CompilerFlags.COROUTINE else: flags |= CompilerFlags.ASYNC_GENERATOR # If the code was not asynchronous before determine if it should now be # asynchronous based on the opcode and the is_async argument. else: if sure_async: # YIELD_FROM is not allowed in async generator if sure_generator: flags |= CompilerFlags.ASYNC_GENERATOR else: flags |= CompilerFlags.COROUTINE elif maybe_generator: if is_async: if sure_generator: flags |= CompilerFlags.ASYNC_GENERATOR else: flags |= CompilerFlags.COROUTINE else: flags |= CompilerFlags.GENERATOR elif is_async: flags |= CompilerFlags.COROUTINE # If the code should not be asynchronous, check first it is possible and # next set the GENERATOR flag if relevant else: if sure_async: raise ValueError( "The is_async argument is False but bytecodes " "that can only be used in async functions have " "been detected." ) if maybe_generator: flags |= CompilerFlags.GENERATOR flags |= bytecode.flags & CompilerFlags.FUTURE_GENERATOR_STOP return flags
Infer the proper flags for a bytecode based on the instructions. Because the bytecode does not have enough context to guess if a function is asynchronous the algorithm tries to be conservative and will never turn a previously async code into a sync one. Parameters ---------- bytecode : Bytecode | ConcreteBytecode | ControlFlowGraph Bytecode for which to infer the proper flags is_async : bool | None, optional Force the code to be marked as asynchronous if True, prevent it from being marked as asynchronous if False and simply infer the best solution based on the opcode and the existing flag if None.
177,879
import sys from _pydevd_frame_eval.vendored import bytecode as _bytecode from _pydevd_frame_eval.vendored.bytecode.concrete import ConcreteInstr from _pydevd_frame_eval.vendored.bytecode.flags import CompilerFlags from _pydevd_frame_eval.vendored.bytecode.instr import Label, SetLineno, Instr class SetLineno: __slots__ = ("_lineno",) def __init__(self, lineno): _check_lineno(lineno) self._lineno = lineno def lineno(self): return self._lineno def __eq__(self, other): if not isinstance(other, SetLineno): return False return self._lineno == other._lineno The provided code snippet includes necessary dependencies for implementing the `_compute_stack_size` function. Write a Python function `def _compute_stack_size(block, size, maxsize, *, check_pre_and_post=True)` to solve the following problem: Generator used to reduce the use of function stacks. This allows to avoid nested recursion and allow to treat more cases. HOW-TO: Following the methods of Trampoline (see https://en.wikipedia.org/wiki/Trampoline_(computing)), We yield either: - the arguments that would be used in the recursive calls, i.e, 'yield block, size, maxsize' instead of making a recursive call '_compute_stack_size(block, size, maxsize)', if we encounter an instruction jumping to another block or if the block is linked to another one (ie `next_block` is set) - the required stack from the stack if we went through all the instructions or encountered an unconditional jump. In the first case, the calling function is then responsible for creating a new generator with those arguments, iterating over it till exhaustion to determine the stacksize required by the block and resuming this function with the determined stacksize. Here is the function: def _compute_stack_size(block, size, maxsize, *, check_pre_and_post=True): """Generator used to reduce the use of function stacks. This allows to avoid nested recursion and allow to treat more cases. HOW-TO: Following the methods of Trampoline (see https://en.wikipedia.org/wiki/Trampoline_(computing)), We yield either: - the arguments that would be used in the recursive calls, i.e, 'yield block, size, maxsize' instead of making a recursive call '_compute_stack_size(block, size, maxsize)', if we encounter an instruction jumping to another block or if the block is linked to another one (ie `next_block` is set) - the required stack from the stack if we went through all the instructions or encountered an unconditional jump. In the first case, the calling function is then responsible for creating a new generator with those arguments, iterating over it till exhaustion to determine the stacksize required by the block and resuming this function with the determined stacksize. """ # If the block is currently being visited (seen = True) or if it was visited # previously by using a larger starting size than the one in use, return the # maxsize. if block.seen or block.startsize >= size: yield maxsize def update_size(pre_delta, post_delta, size, maxsize): size += pre_delta if size < 0: msg = "Failed to compute stacksize, got negative size" raise RuntimeError(msg) size += post_delta maxsize = max(maxsize, size) return size, maxsize # Prevent recursive visit of block if two blocks are nested (jump from one # to the other). block.seen = True block.startsize = size for instr in block: # Ignore SetLineno if isinstance(instr, SetLineno): continue # For instructions with a jump first compute the stacksize required when the # jump is taken. if instr.has_jump(): effect = ( instr.pre_and_post_stack_effect(jump=True) if check_pre_and_post else (instr.stack_effect(jump=True), 0) ) taken_size, maxsize = update_size(*effect, size, maxsize) # Yield the parameters required to compute the stacksize required # by the block to which the jumnp points to and resume when we now # the maxsize. maxsize = yield instr.arg, taken_size, maxsize # For unconditional jumps abort early since the other instruction will # never be seen. if instr.is_uncond_jump(): block.seen = False yield maxsize # jump=False: non-taken path of jumps, or any non-jump effect = ( instr.pre_and_post_stack_effect(jump=False) if check_pre_and_post else (instr.stack_effect(jump=False), 0) ) size, maxsize = update_size(*effect, size, maxsize) if block.next_block: maxsize = yield block.next_block, size, maxsize block.seen = False yield maxsize
Generator used to reduce the use of function stacks. This allows to avoid nested recursion and allow to treat more cases. HOW-TO: Following the methods of Trampoline (see https://en.wikipedia.org/wiki/Trampoline_(computing)), We yield either: - the arguments that would be used in the recursive calls, i.e, 'yield block, size, maxsize' instead of making a recursive call '_compute_stack_size(block, size, maxsize)', if we encounter an instruction jumping to another block or if the block is linked to another one (ie `next_block` is set) - the required stack from the stack if we went through all the instructions or encountered an unconditional jump. In the first case, the calling function is then responsible for creating a new generator with those arguments, iterating over it till exhaustion to determine the stacksize required by the block and resuming this function with the determined stacksize.
177,880
def _fix_contents(filename, contents): import re contents = re.sub( r"from bytecode", r'from _pydevd_frame_eval.vendored.bytecode', contents, flags=re.MULTILINE ) contents = re.sub( r"import bytecode", r'from _pydevd_frame_eval.vendored import bytecode', contents, flags=re.MULTILINE ) # This test will import the wrong setup (we're not interested in it). contents = re.sub( r"def test_version\(self\):", r'def skip_test_version(self):', contents, flags=re.MULTILINE ) if filename.startswith('test_'): if 'pytestmark' not in contents: pytest_mark = ''' import pytest from tests_python.debugger_unittest import IS_PY36_OR_GREATER, IS_CPYTHON from tests_python.debug_constants import TEST_CYTHON pytestmark = pytest.mark.skipif(not IS_PY36_OR_GREATER or not IS_CPYTHON or not TEST_CYTHON, reason='Requires CPython >= 3.6') ''' contents = pytest_mark + contents return contents
null
177,881
import sys from _pydev_bundle import pydev_log from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_comm import get_global_debugger from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info def _pydev_stop_at_break(line): frame = sys._getframe(1) # print('pydevd SET TRACING at ', line, 'curr line', frame.f_lineno) t = threading.current_thread() try: additional_info = t.additional_info except: additional_info = set_additional_thread_info(t) if additional_info.is_tracing: return additional_info.is_tracing += 1 try: py_db = get_global_debugger() if py_db is None: return pydev_log.debug("Setting f_trace due to frame eval mode in file: %s on line %s", frame.f_code.co_filename, line) additional_info.trace_suspend_type = 'frame_eval' pydevd_frame_eval_cython_wrapper = sys.modules['_pydevd_frame_eval.pydevd_frame_eval_cython_wrapper'] thread_info = pydevd_frame_eval_cython_wrapper.get_thread_info_py() if thread_info.thread_trace_func is not None: frame.f_trace = thread_info.thread_trace_func else: frame.f_trace = py_db.get_thread_local_trace_func() finally: additional_info.is_tracing -= 1 def update_globals_dict(globals_dict): new_globals = {'_pydev_stop_at_break': _pydev_stop_at_break} globals_dict.update(new_globals)
null
177,882
import sys from _pydev_bundle import pydev_log from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_comm import get_global_debugger from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info def _get_line_for_frame(frame): # it's absolutely necessary to reset tracing function for frame in order to get the real line number tracing_func = frame.f_trace frame.f_trace = None line = frame.f_lineno frame.f_trace = tracing_func return line
null
177,883
import sys from _pydev_bundle import pydev_log from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_comm import get_global_debugger from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info NORM_PATHS_AND_BASE_CONTAINER = {} def get_abs_path_real_path_and_base_from_frame(frame, NORM_PATHS_AND_BASE_CONTAINER=NORM_PATHS_AND_BASE_CONTAINER): try: return NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: # This one is just internal (so, does not need any kind of client-server translation) f = frame.f_code.co_filename if f is not None and f.startswith (('build/bdist.', 'build\\bdist.')): # files from eggs in Python 2.7 have paths like build/bdist.linux-x86_64/egg/<path-inside-egg> f = frame.f_globals['__file__'] if get_abs_path_real_path_and_base_from_file is None: # Interpreter shutdown if not f: # i.e.: it's possible that the user compiled code with an empty string (consider # it as <string> in this case). f = '<string>' i = max(f.rfind('/'), f.rfind('\\')) return f, f, f[i + 1:] ret = get_abs_path_real_path_and_base_from_file(f) # Also cache based on the frame.f_code.co_filename (if we had it inside build/bdist it can make a difference). NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] = ret return ret The provided code snippet includes necessary dependencies for implementing the `_pydev_needs_stop_at_break` function. Write a Python function `def _pydev_needs_stop_at_break(line)` to solve the following problem: We separate the functionality into 2 functions so that we can generate a bytecode which generates a spurious line change so that we can do: if _pydev_needs_stop_at_break(): # Set line to line -1 _pydev_stop_at_break() # then, proceed to go to the current line # (which will then trigger a line event). Here is the function: def _pydev_needs_stop_at_break(line): ''' We separate the functionality into 2 functions so that we can generate a bytecode which generates a spurious line change so that we can do: if _pydev_needs_stop_at_break(): # Set line to line -1 _pydev_stop_at_break() # then, proceed to go to the current line # (which will then trigger a line event). ''' t = threading.current_thread() try: additional_info = t.additional_info except: additional_info = set_additional_thread_info(t) if additional_info.is_tracing: return False additional_info.is_tracing += 1 try: frame = sys._getframe(1) # print('pydev needs stop at break?', line, 'curr line', frame.f_lineno, 'curr trace', frame.f_trace) if frame.f_trace is not None: # i.e.: this frame is already being traced, thus, we don't need to use programmatic breakpoints. return False py_db = get_global_debugger() if py_db is None: return False try: abs_path_real_path_and_base = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: abs_path_real_path_and_base = get_abs_path_real_path_and_base_from_frame(frame) canonical_normalized_filename = abs_path_real_path_and_base[1] try: python_breakpoint = py_db.breakpoints[canonical_normalized_filename][line] except: # print("Couldn't find breakpoint in the file %s on line %s" % (frame.f_code.co_filename, line)) # Could be KeyError if line is not there or TypeError if breakpoints_for_file is None. # Note: using catch-all exception for performance reasons (if the user adds a breakpoint # and then removes it after hitting it once, this method added for the programmatic # breakpoint will keep on being called and one of those exceptions will always be raised # here). return False if python_breakpoint: # print('YES') return True finally: additional_info.is_tracing -= 1 return False
We separate the functionality into 2 functions so that we can generate a bytecode which generates a spurious line change so that we can do: if _pydev_needs_stop_at_break(): # Set line to line -1 _pydev_stop_at_break() # then, proceed to go to the current line # (which will then trigger a line event).
177,884
from collections import namedtuple import dis from functools import partial import itertools import os.path import sys from _pydevd_frame_eval.vendored import bytecode from _pydevd_frame_eval.vendored.bytecode.instr import Instr, Label from _pydev_bundle import pydev_log from _pydevd_frame_eval.pydevd_frame_tracing import _pydev_stop_at_break, _pydev_needs_stop_at_break DEBUG = False def _get_code_line_info(code_obj): line_to_offset = {} first_line = None last_line = None for offset, line in dis.findlinestarts(code_obj): line_to_offset[line] = offset if line_to_offset: first_line = min(line_to_offset) last_line = max(line_to_offset) return _CodeLineInfo(line_to_offset, first_line, last_line) if DEBUG: debug_helper = DebugHelper() def get_instructions_to_add( stop_at_line, _pydev_stop_at_break=_pydev_stop_at_break, _pydev_needs_stop_at_break=_pydev_needs_stop_at_break ): ''' This is the bytecode for something as: if _pydev_needs_stop_at_break(): _pydev_stop_at_break() but with some special handling for lines. ''' # Good reference to how things work regarding line numbers and jumps: # https://github.com/python/cpython/blob/3.6/Objects/lnotab_notes.txt # Usually use a stop line -1, but if that'd be 0, using line +1 is ok too. spurious_line = stop_at_line - 1 if spurious_line <= 0: spurious_line = stop_at_line + 1 label = Label() return [ # -- if _pydev_needs_stop_at_break(): Instr("LOAD_CONST", _pydev_needs_stop_at_break, lineno=stop_at_line), Instr("LOAD_CONST", stop_at_line, lineno=stop_at_line), Instr("CALL_FUNCTION", 1, lineno=stop_at_line), Instr("POP_JUMP_IF_FALSE", label, lineno=stop_at_line), # -- _pydev_stop_at_break() # # Note that this has line numbers -1 so that when the NOP just below # is executed we have a spurious line event. Instr("LOAD_CONST", _pydev_stop_at_break, lineno=spurious_line), Instr("LOAD_CONST", stop_at_line, lineno=spurious_line), Instr("CALL_FUNCTION", 1, lineno=spurious_line), Instr("POP_TOP", lineno=spurious_line), # Reason for the NOP: Python will give us a 'line' trace event whenever we forward jump to # the first instruction of a line, so, in the case where we haven't added a programmatic # breakpoint (either because we didn't hit a breakpoint anymore or because it was already # tracing), we don't want the spurious line event due to the line change, so, we make a jump # to the instruction right after the NOP so that the spurious line event is NOT generated in # this case (otherwise we'd have a line event even if the line didn't change). Instr("NOP", lineno=stop_at_line), label, ] class _HelperBytecodeList(object): ''' A helper double-linked list to make the manipulation a bit easier (so that we don't need to keep track of indices that change) and performant (because adding multiple items to the middle of a regular list isn't ideal). ''' def __init__(self, lst=None): self._head = None self._tail = None if lst: node = self for item in lst: node = node.append(item) def append(self, data): if self._tail is None: node = _Node(data) self._head = self._tail = node return node else: node = self._tail = self.tail.append(data) return node def head(self): node = self._head # Manipulating the node directly may make it unsynchronized. while node.prev: self._head = node = node.prev return node def tail(self): node = self._tail # Manipulating the node directly may make it unsynchronized. while node.next: self._tail = node = node.next return node def __iter__(self): node = self.head while node: yield node.data node = node.next _PREDICT_TABLE = { 'LIST_APPEND': ('JUMP_ABSOLUTE',), 'SET_ADD': ('JUMP_ABSOLUTE',), 'GET_ANEXT': ('LOAD_CONST',), 'GET_AWAITABLE': ('LOAD_CONST',), 'DICT_MERGE': ('CALL_FUNCTION_EX',), 'MAP_ADD': ('JUMP_ABSOLUTE',), 'COMPARE_OP': ('POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE',), 'IS_OP': ('POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE',), 'CONTAINS_OP': ('POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE',), # Note: there are some others with PREDICT on ceval, but they have more logic # and it needs more experimentation to know how it behaves in the static generated # code (and it's only an issue for us if there's actually a line change between # those, so, we don't have to really handle all the cases, only the one where # the line number actually changes from one instruction to the predicted one). } TRACK_MULTIPLE_BRANCHES = sys.version_info[:2] >= (3, 10) FIX_PREDICT = sys.version_info[:2] >= (3, 10) class Label: __slots__ = () The provided code snippet includes necessary dependencies for implementing the `insert_pydevd_breaks` function. Write a Python function `def insert_pydevd_breaks( code_to_modify, breakpoint_lines, code_line_info=None, _pydev_stop_at_break=_pydev_stop_at_break, _pydev_needs_stop_at_break=_pydev_needs_stop_at_break, )` to solve the following problem: Inserts pydevd programmatic breaks into the code (at the given lines). :param breakpoint_lines: set with the lines where we should add breakpoints. :return: tuple(boolean flag whether insertion was successful, modified code). Here is the function: def insert_pydevd_breaks( code_to_modify, breakpoint_lines, code_line_info=None, _pydev_stop_at_break=_pydev_stop_at_break, _pydev_needs_stop_at_break=_pydev_needs_stop_at_break, ): """ Inserts pydevd programmatic breaks into the code (at the given lines). :param breakpoint_lines: set with the lines where we should add breakpoints. :return: tuple(boolean flag whether insertion was successful, modified code). """ if code_line_info is None: code_line_info = _get_code_line_info(code_to_modify) if not code_line_info.line_to_offset: return False, code_to_modify # Create a copy (and make sure we're dealing with a set). breakpoint_lines = set(breakpoint_lines) # Note that we can even generate breakpoints on the first line of code # now, since we generate a spurious line event -- it may be a bit pointless # as we'll stop in the first line and we don't currently stop the tracing after the # user resumes, but in the future, if we do that, this would be a nice # improvement. # if code_to_modify.co_firstlineno in breakpoint_lines: # return False, code_to_modify for line in breakpoint_lines: if line <= 0: # The first line is line 1, so, a break at line 0 is not valid. pydev_log.info('Trying to add breakpoint in invalid line: %s', line) return False, code_to_modify try: b = bytecode.Bytecode.from_code(code_to_modify) if DEBUG: op_number_bytecode = debug_helper.write_bytecode(b, prefix='bytecode.') helper_list = _HelperBytecodeList(b) modified_breakpoint_lines = breakpoint_lines.copy() curr_node = helper_list.head added_breaks_in_lines = set() last_lineno = None while curr_node is not None: instruction = curr_node.data instruction_lineno = getattr(instruction, 'lineno', None) curr_name = getattr(instruction, 'name', None) if FIX_PREDICT: predict_targets = _PREDICT_TABLE.get(curr_name) if predict_targets: # Odd case: the next instruction may have a line number but it doesn't really # appear in the tracing due to the PREDICT() in ceval, so, fix the bytecode so # that it does things the way that ceval actually interprets it. # See: https://mail.python.org/archives/list/python-dev@python.org/thread/CP2PTFCMTK57KM3M3DLJNWGO66R5RVPB/ next_instruction = curr_node.next.data next_name = getattr(next_instruction, 'name', None) if next_name in predict_targets: next_instruction_lineno = getattr(next_instruction, 'lineno', None) if next_instruction_lineno: next_instruction.lineno = None if instruction_lineno is not None: if TRACK_MULTIPLE_BRANCHES: if last_lineno is None: last_lineno = instruction_lineno else: if last_lineno == instruction_lineno: # If the previous is a label, someone may jump into it, so, we need to add # the break even if it's in the same line. if curr_node.prev.data.__class__ != Label: # Skip adding this as the line is still the same. curr_node = curr_node.next continue last_lineno = instruction_lineno else: if instruction_lineno in added_breaks_in_lines: curr_node = curr_node.next continue if instruction_lineno in modified_breakpoint_lines: added_breaks_in_lines.add(instruction_lineno) if curr_node.prev is not None and curr_node.prev.data.__class__ == Label \ and curr_name == 'POP_TOP': # If we have a SETUP_FINALLY where the target is a POP_TOP, we can't change # the target to be the breakpoint instruction (this can crash the interpreter). for new_instruction in get_instructions_to_add( instruction_lineno, _pydev_stop_at_break=_pydev_stop_at_break, _pydev_needs_stop_at_break=_pydev_needs_stop_at_break, ): curr_node = curr_node.append(new_instruction) else: for new_instruction in get_instructions_to_add( instruction_lineno, _pydev_stop_at_break=_pydev_stop_at_break, _pydev_needs_stop_at_break=_pydev_needs_stop_at_break, ): curr_node.prepend(new_instruction) curr_node = curr_node.next b[:] = helper_list if DEBUG: debug_helper.write_bytecode(b, op_number_bytecode, prefix='bytecode.') new_code = b.to_code() except: pydev_log.exception('Error inserting pydevd breaks.') return False, code_to_modify if DEBUG: op_number = debug_helper.write_dis(code_to_modify) debug_helper.write_dis(new_code, op_number) return True, new_code
Inserts pydevd programmatic breaks into the code (at the given lines). :param breakpoint_lines: set with the lines where we should add breakpoints. :return: tuple(boolean flag whether insertion was successful, modified code).
177,885
from . import VENDORED_ROOT from ._util import cwd, iter_all_files def prune_dir(dirname, basename): if basename == '__pycache__': return True elif dirname != 'pydevd': return False elif basename.startswith('pydev'): return False elif basename.startswith('_pydev'): return False return True def exclude_file(dirname, basename): if dirname == 'pydevd': if basename in INCLUDES: return False elif not basename.endswith('.py'): return True elif 'pydev' not in basename: return True return False if basename.endswith('.pyc'): return True return False def cwd(dirname): """A context manager for operating in a different directory.""" orig = os.getcwd() os.chdir(dirname) try: yield orig finally: os.chdir(orig) def iter_all_files(root, prune_dir=None, exclude_file=None): """Yield (dirname, basename, filename) for each file in the tree. This is an alternative to os.walk() that flattens out the tree and with filtering. """ pending = [root] while pending: dirname = pending.pop(0) for result in _iter_files(dirname, pending, prune_dir, exclude_file): yield result def iter_files(): # From the root of pydevd repo, we want only scripts and # subdirectories that constitute the package itself (not helper # scripts, tests etc). But when walking down into those # subdirectories, we want everything below. with cwd(VENDORED_ROOT): return iter_all_files('pydevd', prune_dir, exclude_file)
null
177,886
import json version_json = ''' { "date": "2023-04-03T17:37:14-0700", "dirty": false, "error": null, "full-revisionid": "2f3e0bb7d5984486def3f2e3d246b974cf243b50", "version": "1.6.7" } ''' def get_versions(): return json.loads(version_json)
null
177,887
import itertools import os import signal import threading import time from debugpy import common from debugpy.common import log, util from debugpy.adapter import components, launchers, servers _lock = threading.RLock() _sessions = set() def get(pid): with _lock: return next((session for session in _sessions if session.pid == pid), None)
null
177,888
import itertools import os import signal import threading import time from debugpy import common from debugpy.common import log, util from debugpy.adapter import components, launchers, servers _lock = threading.RLock() _sessions = set() _sessions_changed = threading.Event() The provided code snippet includes necessary dependencies for implementing the `wait_until_ended` function. Write a Python function `def wait_until_ended()` to solve the following problem: Blocks until all sessions have ended. A session ends when all components that it manages disconnect from it. Here is the function: def wait_until_ended(): """Blocks until all sessions have ended. A session ends when all components that it manages disconnect from it. """ while True: with _lock: if not len(_sessions): return _sessions_changed.clear() _sessions_changed.wait()
Blocks until all sessions have ended. A session ends when all components that it manages disconnect from it.
177,889
from __future__ import annotations import atexit import os import sys import debugpy from debugpy import adapter, common, launcher from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components, servers, sessions class Client(components.Component): """Handles the client side of a debug session.""" message_handler = components.Component.message_handler known_subprocesses: set[servers.Connection] """Server connections to subprocesses that this client has been made aware of. """ class Capabilities(components.Capabilities): PROPERTIES = { "supportsVariableType": False, "supportsVariablePaging": False, "supportsRunInTerminalRequest": False, "supportsMemoryReferences": False, "supportsArgsCanBeInterpretedByShell": False, "supportsStartDebuggingRequest": False, } class Expectations(components.Capabilities): PROPERTIES = { "locale": "en-US", "linesStartAt1": True, "columnsStartAt1": True, "pathFormat": json.enum("path", optional=True), # we don't support "uri" } def __init__(self, sock): if sock == "stdio": log.info("Connecting to client over stdio...", self) self.using_stdio = True stream = messaging.JsonIOStream.from_stdio() # Make sure that nothing else tries to interfere with the stdio streams # that are going to be used for DAP communication from now on. sys.stdin = stdin = open(os.devnull, "r") atexit.register(stdin.close) sys.stdout = stdout = open(os.devnull, "w") atexit.register(stdout.close) else: self.using_stdio = False stream = messaging.JsonIOStream.from_socket(sock) with sessions.Session() as session: super().__init__(session, stream) self.client_id = None """ID of the connecting client. This can be 'test' while running tests.""" self.has_started = False """Whether the "launch" or "attach" request was received from the client, and fully handled. """ self.start_request = None """The "launch" or "attach" request as received from the client. """ self.restart_requested = False """Whether the client requested the debug adapter to be automatically restarted via "restart":true in the start request. """ self._initialize_request = None """The "initialize" request as received from the client, to propagate to the server later.""" self._deferred_events = [] """Deferred events from the launcher and the server that must be propagated only if and when the "launch" or "attach" response is sent. """ self._forward_terminate_request = False self.known_subprocesses = set() session.client = self session.register() # For the transition period, send the telemetry events with both old and new # name. The old one should be removed once the new one lights up. self.channel.send_event( "output", { "category": "telemetry", "output": "ptvsd", "data": {"packageVersion": debugpy.__version__}, }, ) self.channel.send_event( "output", { "category": "telemetry", "output": "debugpy", "data": {"packageVersion": debugpy.__version__}, }, ) def propagate_after_start(self, event): # pydevd starts sending events as soon as we connect, but the client doesn't # expect to see any until it receives the response to "launch" or "attach" # request. If client is not ready yet, save the event instead of propagating # it immediately. if self._deferred_events is not None: self._deferred_events.append(event) log.debug("Propagation deferred.") else: self.client.channel.propagate(event) def _propagate_deferred_events(self): log.debug("Propagating deferred events to {0}...", self.client) for event in self._deferred_events: log.debug("Propagating deferred {0}", event.describe()) self.client.channel.propagate(event) log.info("All deferred events propagated to {0}.", self.client) self._deferred_events = None # Generic event handler. There are no specific handlers for client events, because # there are no events from the client in DAP - but we propagate them if we can, in # case some events appear in future protocol versions. def event(self, event): if self.server: self.server.channel.propagate(event) # Generic request handler, used if there's no specific handler below. def request(self, request): return self.server.channel.delegate(request) def initialize_request(self, request): if self._initialize_request is not None: raise request.isnt_valid("Session is already initialized") self.client_id = request("clientID", "") self.capabilities = self.Capabilities(self, request) self.expectations = self.Expectations(self, request) self._initialize_request = request exception_breakpoint_filters = [ { "filter": "raised", "label": "Raised Exceptions", "default": False, "description": "Break whenever any exception is raised.", }, { "filter": "uncaught", "label": "Uncaught Exceptions", "default": True, "description": "Break when the process is exiting due to unhandled exception.", }, { "filter": "userUnhandled", "label": "User Uncaught Exceptions", "default": False, "description": "Break when exception escapes into library code.", }, ] return { "supportsCompletionsRequest": True, "supportsConditionalBreakpoints": True, "supportsConfigurationDoneRequest": True, "supportsDebuggerProperties": True, "supportsDelayedStackTraceLoading": True, "supportsEvaluateForHovers": True, "supportsExceptionInfoRequest": True, "supportsExceptionOptions": True, "supportsFunctionBreakpoints": True, "supportsHitConditionalBreakpoints": True, "supportsLogPoints": True, "supportsModulesRequest": True, "supportsSetExpression": True, "supportsSetVariable": True, "supportsValueFormattingOptions": True, "supportsTerminateRequest": True, "supportsGotoTargetsRequest": True, "supportsClipboardContext": True, "exceptionBreakpointFilters": exception_breakpoint_filters, "supportsStepInTargetsRequest": True, } # Common code for "launch" and "attach" request handlers. # # See https://github.com/microsoft/vscode/issues/4902#issuecomment-368583522 # for the sequence of request and events necessary to orchestrate the start. def _start_message_handler(f): def handle(self, request): assert request.is_request("launch", "attach") if self._initialize_request is None: raise request.isnt_valid("Session is not initialized yet") if self.launcher or self.server: raise request.isnt_valid("Session is already started") self.session.no_debug = request("noDebug", json.default(False)) if self.session.no_debug: servers.dont_wait_for_first_connection() self.session.debug_options = debug_options = set( request("debugOptions", json.array(str)) ) f(self, request) if request.response is not None: return if self.server: self.server.initialize(self._initialize_request) self._initialize_request = None arguments = request.arguments if self.launcher: redirecting = arguments.get("console") == "internalConsole" if "RedirectOutput" in debug_options: # The launcher is doing output redirection, so we don't need the # server to do it, as well. arguments = dict(arguments) arguments["debugOptions"] = list( debug_options - {"RedirectOutput"} ) redirecting = True if arguments.get("redirectOutput"): arguments = dict(arguments) del arguments["redirectOutput"] redirecting = True arguments["isOutputRedirected"] = redirecting # pydevd doesn't send "initialized", and responds to the start request # immediately, without waiting for "configurationDone". If it changes # to conform to the DAP spec, we'll need to defer waiting for response. try: self.server.channel.request(request.command, arguments) except messaging.NoMoreMessages: # Server closed connection before we could receive the response to # "attach" or "launch" - this can happen when debuggee exits shortly # after starting. It's not an error, but we can't do anything useful # here at this point, either, so just bail out. request.respond({}) self.session.finalize( "{0} disconnected before responding to {1}".format( self.server, json.repr(request.command), ) ) return except messaging.MessageHandlingError as exc: exc.propagate(request) if self.session.no_debug: self.start_request = request self.has_started = True request.respond({}) self._propagate_deferred_events() return # Let the client know that it can begin configuring the adapter. self.channel.send_event("initialized") self.start_request = request return messaging.NO_RESPONSE # will respond on "configurationDone" return handle def launch_request(self, request): from debugpy.adapter import launchers if self.session.id != 1 or len(servers.connections()): raise request.cant_handle('"attach" expected') debug_options = set(request("debugOptions", json.array(str))) # Handling of properties that can also be specified as legacy "debugOptions" flags. # If property is explicitly set to false, but the flag is in "debugOptions", treat # it as an error. Returns None if the property wasn't explicitly set either way. def property_or_debug_option(prop_name, flag_name): assert prop_name[0].islower() and flag_name[0].isupper() value = request(prop_name, bool, optional=True) if value == (): value = None if flag_name in debug_options: if value is False: raise request.isnt_valid( '{0}:false and "debugOptions":[{1}] are mutually exclusive', json.repr(prop_name), json.repr(flag_name), ) value = True return value # "pythonPath" is a deprecated legacy spelling. If "python" is missing, then try # the alternative. But if both are missing, the error message should say "python". python_key = "python" if python_key in request: if "pythonPath" in request: raise request.isnt_valid( '"pythonPath" is not valid if "python" is specified' ) elif "pythonPath" in request: python_key = "pythonPath" python = request(python_key, json.array(str, vectorize=True, size=(0,))) if not len(python): python = [sys.executable] python += request("pythonArgs", json.array(str, size=(0,))) request.arguments["pythonArgs"] = python[1:] request.arguments["python"] = python launcher_python = request("debugLauncherPython", str, optional=True) if launcher_python == (): launcher_python = python[0] program = module = code = () if "program" in request: program = request("program", str) args = [program] request.arguments["processName"] = program if "module" in request: module = request("module", str) args = ["-m", module] request.arguments["processName"] = module if "code" in request: code = request("code", json.array(str, vectorize=True, size=(1,))) args = ["-c", "\n".join(code)] request.arguments["processName"] = "-c" num_targets = len([x for x in (program, module, code) if x != ()]) if num_targets == 0: raise request.isnt_valid( 'either "program", "module", or "code" must be specified' ) elif num_targets != 1: raise request.isnt_valid( '"program", "module", and "code" are mutually exclusive' ) console = request( "console", json.enum( "internalConsole", "integratedTerminal", "externalTerminal", optional=True, ), ) console_title = request("consoleTitle", json.default("Python Debug Console")) # Propagate "args" via CLI so that shell expansion can be applied if requested. target_args = request("args", json.array(str, vectorize=True)) args += target_args # If "args" was a single string rather than an array, shell expansion must be applied. shell_expand_args = len(target_args) > 0 and isinstance( request.arguments["args"], str ) if shell_expand_args: if not self.capabilities["supportsArgsCanBeInterpretedByShell"]: raise request.isnt_valid( 'Shell expansion in "args" is not supported by the client' ) if console == "internalConsole": raise request.isnt_valid( 'Shell expansion in "args" is not available for "console":"internalConsole"' ) cwd = request("cwd", str, optional=True) if cwd == (): # If it's not specified, but we're launching a file rather than a module, # and the specified path has a directory in it, use that. cwd = None if program == () else (os.path.dirname(program) or None) sudo = bool(property_or_debug_option("sudo", "Sudo")) if sudo and sys.platform == "win32": raise request.cant_handle('"sudo":true is not supported on Windows.') on_terminate = request("onTerminate", str, optional=True) if on_terminate: self._forward_terminate_request = on_terminate == "KeyboardInterrupt" launcher_path = request("debugLauncherPath", os.path.dirname(launcher.__file__)) adapter_host = request("debugAdapterHost", "127.0.0.1") try: servers.serve(adapter_host) except Exception as exc: raise request.cant_handle( "{0} couldn't create listener socket for servers: {1}", self.session, exc, ) launchers.spawn_debuggee( self.session, request, [launcher_python], launcher_path, adapter_host, args, shell_expand_args, cwd, console, console_title, sudo, ) def attach_request(self, request): if self.session.no_debug: raise request.isnt_valid('"noDebug" is not supported for "attach"') host = request("host", str, optional=True) port = request("port", int, optional=True) listen = request("listen", dict, optional=True) connect = request("connect", dict, optional=True) pid = request("processId", (int, str), optional=True) sub_pid = request("subProcessId", int, optional=True) on_terminate = request("onTerminate", bool, optional=True) if on_terminate: self._forward_terminate_request = on_terminate == "KeyboardInterrupt" if host != () or port != (): if listen != (): raise request.isnt_valid( '"listen" and "host"/"port" are mutually exclusive' ) if connect != (): raise request.isnt_valid( '"connect" and "host"/"port" are mutually exclusive' ) if listen != (): if connect != (): raise request.isnt_valid( '"listen" and "connect" are mutually exclusive' ) if pid != (): raise request.isnt_valid( '"listen" and "processId" are mutually exclusive' ) if sub_pid != (): raise request.isnt_valid( '"listen" and "subProcessId" are mutually exclusive' ) if pid != () and sub_pid != (): raise request.isnt_valid( '"processId" and "subProcessId" are mutually exclusive' ) if listen != (): if servers.is_serving(): raise request.isnt_valid( 'Multiple concurrent "listen" sessions are not supported' ) host = listen("host", "127.0.0.1") port = listen("port", int) adapter.access_token = None self.restart_requested = request("restart", False) host, port = servers.serve(host, port) else: if not servers.is_serving(): servers.serve() host, port = servers.listener.getsockname() # There are four distinct possibilities here. # # If "processId" is specified, this is attach-by-PID. We need to inject the # debug server into the designated process, and then wait until it connects # back to us. Since the injected server can crash, there must be a timeout. # # If "subProcessId" is specified, this is attach to a known subprocess, likely # in response to a "debugpyAttach" event. If so, the debug server should be # connected already, and thus the wait timeout is zero. # # If "listen" is specified, this is attach-by-socket with the server expected # to connect to the adapter via debugpy.connect(). There is no PID known in # advance, so just wait until the first server connection indefinitely, with # no timeout. # # If "connect" is specified, this is attach-by-socket in which the server has # spawned the adapter via debugpy.listen(). There is no PID known to the client # in advance, but the server connection should be either be there already, or # the server should be connecting shortly, so there must be a timeout. # # In the last two cases, if there's more than one server connection already, # this is a multiprocess re-attach. The client doesn't know the PID, so we just # connect it to the oldest server connection that we have - in most cases, it # will be the one for the root debuggee process, but if it has exited already, # it will be some subprocess. if pid != (): if not isinstance(pid, int): try: pid = int(pid) except Exception: raise request.isnt_valid('"processId" must be parseable as int') debugpy_args = request("debugpyArgs", json.array(str)) def on_output(category, output): self.channel.send_event( "output", { "category": category, "output": output, }, ) try: servers.inject(pid, debugpy_args, on_output) except Exception as e: log.swallow_exception() self.session.finalize( "Error when trying to attach to PID:\n%s" % (str(e),) ) return timeout = common.PROCESS_SPAWN_TIMEOUT pred = lambda conn: conn.pid == pid else: if sub_pid == (): pred = lambda conn: True timeout = common.PROCESS_SPAWN_TIMEOUT if listen == () else None else: pred = lambda conn: conn.pid == sub_pid timeout = 0 self.channel.send_event("debugpyWaitingForServer", {"host": host, "port": port}) conn = servers.wait_for_connection(self.session, pred, timeout) if conn is None: if sub_pid != (): # If we can't find a matching subprocess, it's not always an error - # it might have already exited, or didn't even get a chance to connect. # To prevent the client from complaining, pretend that the "attach" # request was successful, but that the session terminated immediately. request.respond({}) self.session.finalize( 'No known subprocess with "subProcessId":{0}'.format(sub_pid) ) return raise request.cant_handle( ( "Timed out waiting for debug server to connect." if timeout else "There is no debug server connected to this adapter." ), sub_pid, ) try: conn.attach_to_session(self.session) except ValueError: request.cant_handle("{0} is already being debugged.", conn) def configurationDone_request(self, request): if self.start_request is None or self.has_started: request.cant_handle( '"configurationDone" is only allowed during handling of a "launch" ' 'or an "attach" request' ) try: self.has_started = True try: result = self.server.channel.delegate(request) except messaging.NoMoreMessages: # Server closed connection before we could receive the response to # "configurationDone" - this can happen when debuggee exits shortly # after starting. It's not an error, but we can't do anything useful # here at this point, either, so just bail out. request.respond({}) self.start_request.respond({}) self.session.finalize( "{0} disconnected before responding to {1}".format( self.server, json.repr(request.command), ) ) return else: request.respond(result) except messaging.MessageHandlingError as exc: self.start_request.cant_handle(str(exc)) finally: if self.start_request.response is None: self.start_request.respond({}) self._propagate_deferred_events() # Notify the client of any child processes of the debuggee that aren't already # being debugged. for conn in servers.connections(): if conn.server is None and conn.ppid == self.session.pid: self.notify_of_subprocess(conn) def evaluate_request(self, request): propagated_request = self.server.channel.propagate(request) def handle_response(response): request.respond(response.body) propagated_request.on_response(handle_response) return messaging.NO_RESPONSE def pause_request(self, request): request.arguments["threadId"] = "*" return self.server.channel.delegate(request) def continue_request(self, request): request.arguments["threadId"] = "*" try: return self.server.channel.delegate(request) except messaging.NoMoreMessages: # pydevd can sometimes allow the debuggee to exit before the queued # "continue" response gets sent. Thus, a failed "continue" response # indicating that the server disconnected should be treated as success. return {"allThreadsContinued": True} def debugpySystemInfo_request(self, request): result = {"debugpy": {"version": debugpy.__version__}} if self.server: try: pydevd_info = self.server.channel.request("pydevdSystemInfo") except Exception: # If the server has already disconnected, or couldn't handle it, # report what we've got. pass else: result.update(pydevd_info) return result def terminate_request(self, request): # If user specifically requests to terminate, it means that they don't want # debug session auto-restart kicking in. self.restart_requested = False if self._forward_terminate_request: # According to the spec, terminate should try to do a gracefull shutdown. # We do this in the server by interrupting the main thread with a Ctrl+C. # To force the kill a subsequent request would do a disconnect. # # We only do this if the onTerminate option is set though (the default # is a hard-kill for the process and subprocesses). return self.server.channel.delegate(request) self.session.finalize('client requested "terminate"', terminate_debuggee=True) return {} def disconnect_request(self, request): # If user specifically requests to disconnect, it means that they don't want # debug session auto-restart kicking in. self.restart_requested = False terminate_debuggee = request("terminateDebuggee", bool, optional=True) if terminate_debuggee == (): terminate_debuggee = None self.session.finalize('client requested "disconnect"', terminate_debuggee) request.respond({}) if self.using_stdio: # There's no way for the client to reconnect to this adapter once it disconnects # from this session, so close any remaining server connections. servers.stop_serving() log.info("{0} disconnected from stdio; closing remaining server connections.", self) for conn in servers.connections(): try: conn.channel.close() except Exception: log.swallow_exception() def disconnect(self): super().disconnect() def notify_of_subprocess(self, conn): log.info("{1} is a subprocess of {0}.", self, conn) with self.session: if self.start_request is None or conn in self.known_subprocesses: return if "processId" in self.start_request.arguments: log.warning( "Not reporting subprocess for {0}, because the parent process " 'was attached to using "processId" rather than "port".', self.session, ) return log.info("Notifying {0} about {1}.", self, conn) body = dict(self.start_request.arguments) self.known_subprocesses.add(conn) self.session.notify_changed() for key in "processId", "listen", "preLaunchTask", "postDebugTask", "request", "restart": body.pop(key, None) body["name"] = "Subprocess {0}".format(conn.pid) body["subProcessId"] = conn.pid for key in "args", "processName", "pythonArgs": body.pop(key, None) host = body.pop("host", None) port = body.pop("port", None) if "connect" not in body: body["connect"] = {} if "host" not in body["connect"]: body["connect"]["host"] = host if host is not None else "127.0.0.1" if "port" not in body["connect"]: if port is None: _, port = listener.getsockname() body["connect"]["port"] = port if self.capabilities["supportsStartDebuggingRequest"]: self.channel.request("startDebugging", { "request": "attach", "configuration": body, }) else: body["request"] = "attach" self.channel.send_event("debugpyAttach", body) def serve(host, port): global listener listener = sockets.serve("Client", Client, host, port) return listener.getsockname()
null
177,890
from __future__ import annotations import atexit import os import sys import debugpy from debugpy import adapter, common, launcher from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components, servers, sessions def stop_serving(): try: listener.close() except Exception: log.swallow_exception(level="warning")
null
177,891
import functools from debugpy.common import json, log, messaging, util class ComponentNotAvailable(Exception): def __init__(self, type): def missing(session, type): class Missing(object): """A dummy component that raises ComponentNotAvailable whenever some attribute is accessed on it. """ __getattr__ = __setattr__ = lambda self, *_: report() __bool__ = __nonzero__ = lambda self: False def report(): try: raise ComponentNotAvailable(type) except Exception as exc: log.reraise_exception("{0} in {1}", exc, session) return Missing()
null
177,892
import argparse import atexit import codecs import locale import os import sys def _parse_argv(argv): parser = argparse.ArgumentParser() parser.add_argument( "--for-server", type=int, metavar="PORT", help=argparse.SUPPRESS ) parser.add_argument( "--port", type=int, default=None, metavar="PORT", help="start the adapter in debugServer mode on the specified port", ) parser.add_argument( "--host", type=str, default="127.0.0.1", metavar="HOST", help="start the adapter in debugServer mode on the specified host", ) parser.add_argument( "--access-token", type=str, help="access token expected from the server" ) parser.add_argument( "--server-access-token", type=str, help="access token expected by the server" ) parser.add_argument( "--log-dir", type=str, metavar="DIR", help="enable logging and use DIR to save adapter logs", ) parser.add_argument( "--log-stderr", action="store_true", help="enable logging to stderr" ) args = parser.parse_args(argv[1:]) if args.port is None: if args.log_stderr: parser.error("--log-stderr requires --port") if args.for_server is not None: parser.error("--for-server requires --port") return args
null
177,893
import os import subprocess import sys from debugpy import adapter, common from debugpy.common import log, messaging, sockets from debugpy.adapter import components, servers class Launcher(components.Component): """Handles the launcher side of a debug session.""" message_handler = components.Component.message_handler def __init__(self, session, stream): with session: assert not session.launcher super().__init__(session, stream) self.pid = None """Process ID of the debuggee process, as reported by the launcher.""" self.exit_code = None """Exit code of the debuggee process.""" session.launcher = self def process_event(self, event): self.pid = event("systemProcessId", int) self.client.propagate_after_start(event) def output_event(self, event): self.client.propagate_after_start(event) def exited_event(self, event): self.exit_code = event("exitCode", int) # We don't want to tell the client about this just yet, because it will then # want to disconnect, and the launcher might still be waiting for keypress # (if wait-on-exit was enabled). Instead, we'll report the event when we # receive "terminated" from the launcher, right before it exits. def terminated_event(self, event): try: self.client.channel.send_event("exited", {"exitCode": self.exit_code}) except Exception: pass self.channel.close() def terminate_debuggee(self): with self.session: if self.exit_code is None: try: self.channel.request("terminate") except Exception: pass def spawn_debuggee( session, start_request, python, launcher_path, adapter_host, args, shell_expand_args, cwd, console, console_title, sudo, ): # -E tells sudo to propagate environment variables to the target process - this # is necessary for launcher to get DEBUGPY_LAUNCHER_PORT and DEBUGPY_LOG_DIR. cmdline = ["sudo", "-E"] if sudo else [] cmdline += python cmdline += [launcher_path] env = {} arguments = dict(start_request.arguments) if not session.no_debug: _, arguments["port"] = servers.listener.getsockname() arguments["adapterAccessToken"] = adapter.access_token def on_launcher_connected(sock): listener.close() stream = messaging.JsonIOStream.from_socket(sock) Launcher(session, stream) try: listener = sockets.serve( "Launcher", on_launcher_connected, adapter_host, backlog=1 ) except Exception as exc: raise start_request.cant_handle( "{0} couldn't create listener socket for launcher: {1}", session, exc ) try: launcher_host, launcher_port = listener.getsockname() launcher_addr = ( launcher_port if launcher_host == "127.0.0.1" else f"{launcher_host}:{launcher_port}" ) cmdline += [str(launcher_addr), "--"] cmdline += args if log.log_dir is not None: env[str("DEBUGPY_LOG_DIR")] = log.log_dir if log.stderr.levels != {"warning", "error"}: env[str("DEBUGPY_LOG_STDERR")] = str(" ".join(log.stderr.levels)) if console == "internalConsole": log.info("{0} spawning launcher: {1!r}", session, cmdline) try: # If we are talking to the client over stdio, sys.stdin and sys.stdout # are redirected to avoid mangling the DAP message stream. Make sure # the launcher also respects that. subprocess.Popen( cmdline, cwd=cwd, env=dict(list(os.environ.items()) + list(env.items())), stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, ) except Exception as exc: raise start_request.cant_handle("Failed to spawn launcher: {0}", exc) else: log.info('{0} spawning launcher via "runInTerminal" request.', session) session.client.capabilities.require("supportsRunInTerminalRequest") kinds = {"integratedTerminal": "integrated", "externalTerminal": "external"} request_args = { "kind": kinds[console], "title": console_title, "args": cmdline, "env": env, } if cwd is not None: request_args["cwd"] = cwd if shell_expand_args: request_args["argsCanBeInterpretedByShell"] = True try: # It is unspecified whether this request receives a response immediately, or only # after the spawned command has completed running, so do not block waiting for it. session.client.channel.send_request("runInTerminal", request_args) except messaging.MessageHandlingError as exc: exc.propagate(start_request) # If using sudo, it might prompt for password, and launcher won't start running # until the user enters it, so don't apply timeout in that case. if not session.wait_for( lambda: session.launcher, timeout=(None if sudo else common.PROCESS_SPAWN_TIMEOUT), ): raise start_request.cant_handle("Timed out waiting for launcher to connect") try: session.launcher.channel.request(start_request.command, arguments) except messaging.MessageHandlingError as exc: exc.propagate(start_request) if not session.wait_for( lambda: session.launcher.pid is not None, timeout=common.PROCESS_SPAWN_TIMEOUT, ): raise start_request.cant_handle( 'Timed out waiting for "process" event from launcher' ) if session.no_debug: return # Wait for the first incoming connection regardless of the PID - it won't # necessarily match due to the use of stubs like py.exe or "conda run". conn = servers.wait_for_connection( session, lambda conn: True, timeout=common.PROCESS_SPAWN_TIMEOUT ) if conn is None: raise start_request.cant_handle("Timed out waiting for debuggee to spawn") conn.attach_to_session(session) finally: listener.close()
null
177,894
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io listener = None def is_serving(): return listener is not None
null
177,895
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io listener = None def stop_serving(): global listener try: if listener is not None: listener.close() listener = None except Exception: log.swallow_exception(level="warning")
null
177,896
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io _lock = threading.RLock() _connections = [] def connections(): with _lock: return list(_connections)
null
177,897
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io _lock = threading.RLock() _connections = [] _connections_changed = threading.Event() The provided code snippet includes necessary dependencies for implementing the `wait_until_disconnected` function. Write a Python function `def wait_until_disconnected()` to solve the following problem: Blocks until all debug servers disconnect from the adapter. If there are no server connections, waits until at least one is established first, before waiting for it to disconnect. Here is the function: def wait_until_disconnected(): """Blocks until all debug servers disconnect from the adapter. If there are no server connections, waits until at least one is established first, before waiting for it to disconnect. """ while True: _connections_changed.wait() with _lock: _connections_changed.clear() if not len(_connections): return
Blocks until all debug servers disconnect from the adapter. If there are no server connections, waits until at least one is established first, before waiting for it to disconnect.
177,898
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io _lock = threading.RLock() _connections_changed = threading.Event() The provided code snippet includes necessary dependencies for implementing the `dont_wait_for_first_connection` function. Write a Python function `def dont_wait_for_first_connection()` to solve the following problem: Unblocks any pending wait_until_disconnected() call that is waiting on the first server to connect. Here is the function: def dont_wait_for_first_connection(): """Unblocks any pending wait_until_disconnected() call that is waiting on the first server to connect. """ with _lock: _connections_changed.set()
Unblocks any pending wait_until_disconnected() call that is waiting on the first server to connect.
177,899
from __future__ import annotations import os import subprocess import sys import threading import time import debugpy from debugpy import adapter from debugpy.common import json, log, messaging, sockets from debugpy.adapter import components import traceback import io access_token = None listener = None def inject(pid, debugpy_args, on_output): host, port = listener.getsockname() cmdline = [ sys.executable, os.path.dirname(debugpy.__file__), "--connect", host + ":" + str(port), ] if adapter.access_token is not None: cmdline += ["--adapter-access-token", adapter.access_token] cmdline += debugpy_args cmdline += ["--pid", str(pid)] log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline) try: injector = subprocess.Popen( cmdline, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) except Exception as exc: log.swallow_exception( "Failed to inject debug server into process with PID={0}", pid ) raise messaging.MessageHandlingError( "Failed to inject debug server into process with PID={0}: {1}".format( pid, exc ) ) # We need to capture the output of the injector - needed so that it doesn't # get blocked on a write() syscall (besides showing it to the user if it # is taking longer than expected). output_collected = [] output_collected.append("--- Starting attach to pid: {0} ---\n".format(pid)) def capture(stream): nonlocal output_collected try: while True: line = stream.readline() if not line: break line = line.decode("utf-8", "replace") output_collected.append(line) log.info("Injector[PID={0}] output: {1}", pid, line.rstrip()) log.info("Injector[PID={0}] exited.", pid) except Exception: s = io.StringIO() traceback.print_exc(file=s) on_output("stderr", s.getvalue()) threading.Thread( target=capture, name=f"Injector[PID={pid}] stdout", args=(injector.stdout,), daemon=True, ).start() def info_on_timeout(): nonlocal output_collected taking_longer_than_expected = False initial_time = time.time() while True: time.sleep(1) returncode = injector.poll() if returncode is not None: if returncode != 0: # Something didn't work out. Let's print more info to the user. on_output( "stderr", "Attach to PID failed.\n\n", ) old = output_collected output_collected = [] contents = "".join(old) on_output("stderr", "".join(contents)) break elapsed = time.time() - initial_time on_output( "stdout", "Attaching to PID: %s (elapsed: %.2fs).\n" % (pid, elapsed) ) if not taking_longer_than_expected: if elapsed > 10: taking_longer_than_expected = True if sys.platform in ("linux", "linux2"): on_output( "stdout", "\nThe attach to PID is taking longer than expected.\n", ) on_output( "stdout", "On Linux it's possible to customize the value of\n", ) on_output( "stdout", "`PYDEVD_GDB_SCAN_SHARED_LIBRARIES` so that fewer libraries.\n", ) on_output( "stdout", "are scanned when searching for the needed symbols.\n\n", ) on_output( "stdout", "i.e.: set in your environment variables (and restart your editor/client\n", ) on_output( "stdout", "so that it picks up the updated environment variable value):\n\n", ) on_output( "stdout", "PYDEVD_GDB_SCAN_SHARED_LIBRARIES=libdl, libltdl, libc, libfreebl3\n\n", ) on_output( "stdout", "-- the actual library may be different (the gdb output typically\n", ) on_output( "stdout", "-- writes the libraries that will be used, so, it should be possible\n", ) on_output( "stdout", "-- to test other libraries if the above doesn't work).\n\n", ) if taking_longer_than_expected: # If taking longer than expected, start showing the actual output to the user. old = output_collected output_collected = [] contents = "".join(old) if contents: on_output("stderr", contents) threading.Thread( target=info_on_timeout, name=f"Injector[PID={pid}] info on timeout", daemon=True ).start()
null
177,900
from __future__ import annotations import functools import typing from debugpy import _version def _api(cancelable=False): def apply(f): @functools.wraps(f) def wrapper(*args, **kwargs): from debugpy.server import api wrapped = getattr(api, f.__name__) return wrapped(*args, **kwargs) if cancelable: def cancel(*args, **kwargs): from debugpy.server import api wrapped = getattr(api, f.__name__) return wrapped.cancel(*args, **kwargs) wrapper.cancel = cancel return wrapper return apply
null
177,901
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `log_to` function. Write a Python function `def log_to(__path: str) -> None` to solve the following problem: Generate detailed debugpy logs in the specified directory. The directory must already exist. Several log files are generated, one for every process involved in the debug session. Here is the function: def log_to(__path: str) -> None: """Generate detailed debugpy logs in the specified directory. The directory must already exist. Several log files are generated, one for every process involved in the debug session. """
Generate detailed debugpy logs in the specified directory. The directory must already exist. Several log files are generated, one for every process involved in the debug session.
177,902
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `configure` function. Write a Python function `def configure(__properties: dict[str, typing.Any] | None = None, **kwargs) -> None` to solve the following problem: Sets debug configuration properties that cannot be set in the "attach" request, because they must be applied as early as possible in the process being debugged. For example, a "launch" configuration with subprocess debugging disabled can be defined entirely in JSON:: { "request": "launch", "subProcess": false, ... } But the same cannot be done with "attach", because "subProcess" must be known at the point debugpy starts tracing execution. Thus, it is not available in JSON, and must be omitted:: { "request": "attach", ... } and set from within the debugged process instead:: debugpy.configure(subProcess=False) debugpy.listen(...) Properties to set can be passed either as a single dict argument, or as separate keyword arguments:: debugpy.configure({"subProcess": False}) Here is the function: def configure(__properties: dict[str, typing.Any] | None = None, **kwargs) -> None: """Sets debug configuration properties that cannot be set in the "attach" request, because they must be applied as early as possible in the process being debugged. For example, a "launch" configuration with subprocess debugging disabled can be defined entirely in JSON:: { "request": "launch", "subProcess": false, ... } But the same cannot be done with "attach", because "subProcess" must be known at the point debugpy starts tracing execution. Thus, it is not available in JSON, and must be omitted:: { "request": "attach", ... } and set from within the debugged process instead:: debugpy.configure(subProcess=False) debugpy.listen(...) Properties to set can be passed either as a single dict argument, or as separate keyword arguments:: debugpy.configure({"subProcess": False}) """
Sets debug configuration properties that cannot be set in the "attach" request, because they must be applied as early as possible in the process being debugged. For example, a "launch" configuration with subprocess debugging disabled can be defined entirely in JSON:: { "request": "launch", "subProcess": false, ... } But the same cannot be done with "attach", because "subProcess" must be known at the point debugpy starts tracing execution. Thus, it is not available in JSON, and must be omitted:: { "request": "attach", ... } and set from within the debugged process instead:: debugpy.configure(subProcess=False) debugpy.listen(...) Properties to set can be passed either as a single dict argument, or as separate keyword arguments:: debugpy.configure({"subProcess": False})
177,903
from __future__ import annotations import functools import typing from debugpy import _version Endpoint = typing.Tuple[str, int] The provided code snippet includes necessary dependencies for implementing the `listen` function. Write a Python function `def listen( __endpoint: Endpoint | int, *, in_process_debug_adapter: bool = False ) -> Endpoint` to solve the following problem: Starts a debug adapter debugging this process, that listens for incoming socket connections from clients on the specified address. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `in_process_debug_adapter`: by default a separate python process is spawned and used to communicate with the client as the debug adapter. By setting the value of `in_process_debug_adapter` to True a new python process is not spawned. Note: the con of setting `in_process_debug_adapter` to True is that subprocesses won't be automatically debugged. Returns the interface and the port on which the debug adapter is actually listening, in the same format as `__endpoint`. This may be different from address if port was 0 in the latter, in which case the adapter will pick some unused ephemeral port to listen on. This function does't wait for a client to connect to the debug adapter that it starts. Use `wait_for_client` to block execution until the client connects. Here is the function: def listen( __endpoint: Endpoint | int, *, in_process_debug_adapter: bool = False ) -> Endpoint: """Starts a debug adapter debugging this process, that listens for incoming socket connections from clients on the specified address. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `in_process_debug_adapter`: by default a separate python process is spawned and used to communicate with the client as the debug adapter. By setting the value of `in_process_debug_adapter` to True a new python process is not spawned. Note: the con of setting `in_process_debug_adapter` to True is that subprocesses won't be automatically debugged. Returns the interface and the port on which the debug adapter is actually listening, in the same format as `__endpoint`. This may be different from address if port was 0 in the latter, in which case the adapter will pick some unused ephemeral port to listen on. This function does't wait for a client to connect to the debug adapter that it starts. Use `wait_for_client` to block execution until the client connects. """
Starts a debug adapter debugging this process, that listens for incoming socket connections from clients on the specified address. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `in_process_debug_adapter`: by default a separate python process is spawned and used to communicate with the client as the debug adapter. By setting the value of `in_process_debug_adapter` to True a new python process is not spawned. Note: the con of setting `in_process_debug_adapter` to True is that subprocesses won't be automatically debugged. Returns the interface and the port on which the debug adapter is actually listening, in the same format as `__endpoint`. This may be different from address if port was 0 in the latter, in which case the adapter will pick some unused ephemeral port to listen on. This function does't wait for a client to connect to the debug adapter that it starts. Use `wait_for_client` to block execution until the client connects.
177,904
from __future__ import annotations import functools import typing from debugpy import _version Endpoint = typing.Tuple[str, int] The provided code snippet includes necessary dependencies for implementing the `connect` function. Write a Python function `def connect(__endpoint: Endpoint | int, *, access_token: str | None = None) -> Endpoint` to solve the following problem: Tells an existing debug adapter instance that is listening on the specified address to debug this process. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `access_token` must be the same value that was passed to the adapter via the `--server-access-token` command-line switch. This function does't wait for a client to connect to the debug adapter that it connects to. Use `wait_for_client` to block execution until the client connects. Here is the function: def connect(__endpoint: Endpoint | int, *, access_token: str | None = None) -> Endpoint: """Tells an existing debug adapter instance that is listening on the specified address to debug this process. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `access_token` must be the same value that was passed to the adapter via the `--server-access-token` command-line switch. This function does't wait for a client to connect to the debug adapter that it connects to. Use `wait_for_client` to block execution until the client connects. """
Tells an existing debug adapter instance that is listening on the specified address to debug this process. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `access_token` must be the same value that was passed to the adapter via the `--server-access-token` command-line switch. This function does't wait for a client to connect to the debug adapter that it connects to. Use `wait_for_client` to block execution until the client connects.
177,905
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `wait_for_client` function. Write a Python function `def wait_for_client() -> None` to solve the following problem: If there is a client connected to the debug adapter that is debugging this process, returns immediately. Otherwise, blocks until a client connects to the adapter. While this function is waiting, it can be canceled by calling `wait_for_client.cancel()` from another thread. Here is the function: def wait_for_client() -> None: """If there is a client connected to the debug adapter that is debugging this process, returns immediately. Otherwise, blocks until a client connects to the adapter. While this function is waiting, it can be canceled by calling `wait_for_client.cancel()` from another thread. """
If there is a client connected to the debug adapter that is debugging this process, returns immediately. Otherwise, blocks until a client connects to the adapter. While this function is waiting, it can be canceled by calling `wait_for_client.cancel()` from another thread.
177,906
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `is_client_connected` function. Write a Python function `def is_client_connected() -> bool` to solve the following problem: True if a client is connected to the debug adapter that is debugging this process. Here is the function: def is_client_connected() -> bool: """True if a client is connected to the debug adapter that is debugging this process. """
True if a client is connected to the debug adapter that is debugging this process.
177,907
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `breakpoint` function. Write a Python function `def breakpoint() -> None` to solve the following problem: If a client is connected to the debug adapter that is debugging this process, pauses execution of all threads, and simulates a breakpoint being hit at the line following the call. It is also registered as the default handler for builtins.breakpoint(). Here is the function: def breakpoint() -> None: """If a client is connected to the debug adapter that is debugging this process, pauses execution of all threads, and simulates a breakpoint being hit at the line following the call. It is also registered as the default handler for builtins.breakpoint(). """
If a client is connected to the debug adapter that is debugging this process, pauses execution of all threads, and simulates a breakpoint being hit at the line following the call. It is also registered as the default handler for builtins.breakpoint().
177,908
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `debug_this_thread` function. Write a Python function `def debug_this_thread() -> None` to solve the following problem: Makes the debugger aware of the current thread. Must be called on any background thread that is started by means other than the usual Python APIs (i.e. the "threading" module), in order for breakpoints to work on that thread. Here is the function: def debug_this_thread() -> None: """Makes the debugger aware of the current thread. Must be called on any background thread that is started by means other than the usual Python APIs (i.e. the "threading" module), in order for breakpoints to work on that thread. """
Makes the debugger aware of the current thread. Must be called on any background thread that is started by means other than the usual Python APIs (i.e. the "threading" module), in order for breakpoints to work on that thread.
177,909
from __future__ import annotations import functools import typing from debugpy import _version The provided code snippet includes necessary dependencies for implementing the `trace_this_thread` function. Write a Python function `def trace_this_thread(__should_trace: bool)` to solve the following problem: Tells the debug adapter to enable or disable tracing on the current thread. When the thread is traced, the debug adapter can detect breakpoints being hit, but execution is slower, especially in functions that have any breakpoints set in them. Disabling tracing when breakpoints are not anticipated to be hit can improve performance. It can also be used to skip breakpoints on a particular thread. Tracing is automatically disabled for all threads when there is no client connected to the debug adapter. Here is the function: def trace_this_thread(__should_trace: bool): """Tells the debug adapter to enable or disable tracing on the current thread. When the thread is traced, the debug adapter can detect breakpoints being hit, but execution is slower, especially in functions that have any breakpoints set in them. Disabling tracing when breakpoints are not anticipated to be hit can improve performance. It can also be used to skip breakpoints on a particular thread. Tracing is automatically disabled for all threads when there is no client connected to the debug adapter. """
Tells the debug adapter to enable or disable tracing on the current thread. When the thread is traced, the debug adapter can detect breakpoints being hit, but execution is slower, especially in functions that have any breakpoints set in them. Disabling tracing when breakpoints are not anticipated to be hit can improve performance. It can also be used to skip breakpoints on a particular thread. Tracing is automatically disabled for all threads when there is no client connected to the debug adapter.
177,910
import ctypes from ctypes.wintypes import BOOL, DWORD, HANDLE, LARGE_INTEGER, LPCSTR, UINT from debugpy.common import log def _errcheck(is_error_result=(lambda result: not result)): def impl(result, func, args): if is_error_result(result): log.debug("{0} returned {1}", func.__name__, result) raise ctypes.WinError() else: return result return impl
null
177,911
import os import sys import debugpy from debugpy import launcher from debugpy.common import json from debugpy.launcher import debuggee import json def launch_request(request): debug_options = set(request("debugOptions", json.array(str))) # Handling of properties that can also be specified as legacy "debugOptions" flags. # If property is explicitly set to false, but the flag is in "debugOptions", treat # it as an error. Returns None if the property wasn't explicitly set either way. def property_or_debug_option(prop_name, flag_name): assert prop_name[0].islower() and flag_name[0].isupper() value = request(prop_name, bool, optional=True) if value == (): value = None if flag_name in debug_options: if value is False: raise request.isnt_valid( '{0}:false and "debugOptions":[{1}] are mutually exclusive', json.repr(prop_name), json.repr(flag_name), ) value = True return value python = request("python", json.array(str, size=(1,))) cmdline = list(python) if not request("noDebug", json.default(False)): # see https://github.com/microsoft/debugpy/issues/861 if sys.version_info[:2] >= (3, 11): cmdline += ["-X", "frozen_modules=off"] port = request("port", int) cmdline += [ os.path.dirname(debugpy.__file__), "--connect", launcher.adapter_host + ":" + str(port), ] if not request("subProcess", True): cmdline += ["--configure-subProcess", "False"] qt_mode = request( "qt", json.enum( "none", "auto", "pyside", "pyside2", "pyqt4", "pyqt5", optional=True ), ) cmdline += ["--configure-qt", qt_mode] adapter_access_token = request("adapterAccessToken", str, optional=True) if adapter_access_token != (): cmdline += ["--adapter-access-token", adapter_access_token] debugpy_args = request("debugpyArgs", json.array(str)) cmdline += debugpy_args # Use the copy of arguments that was propagated via the command line rather than # "args" in the request itself, to allow for shell expansion. cmdline += sys.argv[1:] process_name = request("processName", sys.executable) env = os.environ.copy() env_changes = request("env", json.object((str, type(None)))) if sys.platform == "win32": # Environment variables are case-insensitive on Win32, so we need to normalize # both dicts to make sure that env vars specified in the debug configuration # overwrite the global env vars correctly. If debug config has entries that # differ in case only, that's an error. env = {k.upper(): v for k, v in os.environ.items()} new_env_changes = {} for k, v in env_changes.items(): k_upper = k.upper() if k_upper in new_env_changes: if new_env_changes[k_upper] == v: continue else: raise request.isnt_valid( 'Found duplicate in "env": {0}.'.format(k_upper) ) new_env_changes[k_upper] = v env_changes = new_env_changes if "DEBUGPY_TEST" in env: # If we're running as part of a debugpy test, make sure that codecov is not # applied to the debuggee, since it will conflict with pydevd. env.pop("COV_CORE_SOURCE", None) env.update(env_changes) env = {k: v for k, v in env.items() if v is not None} if request("gevent", False): env["GEVENT_SUPPORT"] = "True" console = request( "console", json.enum( "internalConsole", "integratedTerminal", "externalTerminal", optional=True ), ) redirect_output = property_or_debug_option("redirectOutput", "RedirectOutput") if redirect_output is None: # If neither the property nor the option were specified explicitly, choose # the default depending on console type - "internalConsole" needs it to # provide any output at all, but it's unnecessary for the terminals. redirect_output = console == "internalConsole" if redirect_output: # sys.stdout buffering must be disabled - otherwise we won't see the output # at all until the buffer fills up. env["PYTHONUNBUFFERED"] = "1" # Force UTF-8 output to minimize data loss due to re-encoding. env["PYTHONIOENCODING"] = "utf-8" if property_or_debug_option("waitOnNormalExit", "WaitOnNormalExit"): if console == "internalConsole": raise request.isnt_valid( '"waitOnNormalExit" is not supported for "console":"internalConsole"' ) debuggee.wait_on_exit_predicates.append(lambda code: code == 0) if property_or_debug_option("waitOnAbnormalExit", "WaitOnAbnormalExit"): if console == "internalConsole": raise request.isnt_valid( '"waitOnAbnormalExit" is not supported for "console":"internalConsole"' ) debuggee.wait_on_exit_predicates.append(lambda code: code != 0) debuggee.spawn(process_name, cmdline, env, redirect_output) return {}
null
177,912
import os import sys import debugpy from debugpy import launcher from debugpy.common import json from debugpy.launcher import debuggee def terminate_request(request): del debuggee.wait_on_exit_predicates[:] request.respond({}) debuggee.kill()
null
177,913
import os import sys import debugpy from debugpy import launcher from debugpy.common import json from debugpy.launcher import debuggee def disconnect(): del debuggee.wait_on_exit_predicates[:] debuggee.kill()
null
177,914
import inspect import os import sys def force_bytes(s, encoding, errors="strict"): """Converts s to bytes, using the provided encoding. If s is already bytes, it is returned as is. If errors="strict" and s is bytes, its encoding is verified by decoding it; UnicodeError is raised if it cannot be decoded. """ if isinstance(s, str): return s.encode(encoding, errors) else: s = bytes(s) if errors == "strict": # Return value ignored - invoked solely for verification. s.decode(encoding, errors) return s The provided code snippet includes necessary dependencies for implementing the `force_ascii` function. Write a Python function `def force_ascii(s, errors="strict")` to solve the following problem: Same as force_bytes(s, "ascii", errors) Here is the function: def force_ascii(s, errors="strict"): """Same as force_bytes(s, "ascii", errors)""" return force_bytes(s, "ascii", errors)
Same as force_bytes(s, "ascii", errors)
177,915
import inspect import os import sys def force_bytes(s, encoding, errors="strict"): """Converts s to bytes, using the provided encoding. If s is already bytes, it is returned as is. If errors="strict" and s is bytes, its encoding is verified by decoding it; UnicodeError is raised if it cannot be decoded. """ if isinstance(s, str): return s.encode(encoding, errors) else: s = bytes(s) if errors == "strict": # Return value ignored - invoked solely for verification. s.decode(encoding, errors) return s The provided code snippet includes necessary dependencies for implementing the `force_utf8` function. Write a Python function `def force_utf8(s, errors="strict")` to solve the following problem: Same as force_bytes(s, "utf8", errors) Here is the function: def force_utf8(s, errors="strict"): """Same as force_bytes(s, "utf8", errors)""" return force_bytes(s, "utf8", errors)
Same as force_bytes(s, "utf8", errors)
177,916
from __future__ import annotations import collections import contextlib import functools import itertools import os import socket import sys import threading from debugpy.common import json, log, util from debugpy.common.util import hide_thread_from_debugger class MessageDict(collections.OrderedDict): """A specialized dict that is used for JSON message payloads - Request.arguments, Response.body, and Event.body. For all members that normally throw KeyError when a requested key is missing, this dict raises InvalidMessageError instead. Thus, a message handler can skip checks for missing properties, and just work directly with the payload on the assumption that it is valid according to the protocol specification; if anything is missing, it will be reported automatically in the proper manner. If the value for the requested key is itself a dict, it is returned as is, and not automatically converted to MessageDict. Thus, to enable convenient chaining - e.g. d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than vanilla dicts for all its values, recursively. This is guaranteed for the payload of all freshly received messages (unless and until it is mutated), but there is no such guarantee for outgoing messages. """ def __init__(self, message, items=None): assert message is None or isinstance(message, Message) if items is None: super().__init__() else: super().__init__(items) self.message = message """The Message object that owns this dict. For any instance exposed via a Message object corresponding to some incoming message, it is guaranteed to reference that Message object. There is no similar guarantee for outgoing messages. """ def __repr__(self): try: return format(json.repr(self)) except Exception: return super().__repr__() def __call__(self, key, validate, optional=False): """Like get(), but with validation. The item is first retrieved as if with self.get(key, default=()) - the default value is () rather than None, so that JSON nulls are distinguishable from missing properties. If optional=True, and the value is (), it's returned as is. Otherwise, the item is validated by invoking validate(item) on it. If validate=False, it's treated as if it were (lambda x: x) - i.e. any value is considered valid, and is returned unchanged. If validate is a type or a tuple, it's treated as json.of_type(validate). Otherwise, if validate is not callable(), it's treated as json.default(validate). If validate() returns successfully, the item is substituted with the value it returns - thus, the validator can e.g. replace () with a suitable default value for the property. If validate() raises TypeError or ValueError, raises InvalidMessageError with the same text that applies_to(self.messages). See debugpy.common.json for reusable validators. """ if not validate: validate = lambda x: x elif isinstance(validate, type) or isinstance(validate, tuple): validate = json.of_type(validate, optional=optional) elif not callable(validate): validate = json.default(validate) value = self.get(key, ()) try: value = validate(value) except (TypeError, ValueError) as exc: message = Message if self.message is None else self.message err = str(exc) if not err.startswith("["): err = " " + err raise message.isnt_valid("{0}{1}", json.repr(key), err) return value def _invalid_if_no_key(func): def wrap(self, key, *args, **kwargs): try: return func(self, key, *args, **kwargs) except KeyError: message = Message if self.message is None else self.message raise message.isnt_valid("missing property {0!r}", key) return wrap __getitem__ = _invalid_if_no_key(collections.OrderedDict.__getitem__) __delitem__ = _invalid_if_no_key(collections.OrderedDict.__delitem__) pop = _invalid_if_no_key(collections.OrderedDict.pop) del _invalid_if_no_key The provided code snippet includes necessary dependencies for implementing the `_payload` function. Write a Python function `def _payload(value)` to solve the following problem: JSON validator for message payload. If that value is missing or null, it is treated as if it were {}. Here is the function: def _payload(value): """JSON validator for message payload. If that value is missing or null, it is treated as if it were {}. """ if value is not None and value != (): if isinstance(value, dict): # can be int, str, list... assert isinstance(value, MessageDict) return value # Missing payload. Construct a dummy MessageDict, and make it look like it was # deserialized. See JsonMessageChannel._parse_incoming_message for why it needs # to have associate_with(). def associate_with(message): value.message = message value = MessageDict(None) value.associate_with = associate_with return value
JSON validator for message payload. If that value is missing or null, it is treated as if it were {}.
177,917
import os import sys import time import threading import traceback from debugpy.common import log def dump(): """Dump stacks of all threads in this process, except for the current thread.""" tid = threading.current_thread().ident pid = os.getpid() log.info("Dumping stacks for process {0}...", pid) for t_ident, frame in sys._current_frames().items(): if t_ident == tid: continue for t in threading.enumerate(): if t.ident == tid: t_name = t.name t_daemon = t.daemon break else: t_name = t_daemon = "<unknown>" stack = "".join(traceback.format_stack(frame)) log.info( "Stack of thread {0} (tid={1}, pid={2}, daemon={3}):\n\n{4}", t_name, t_ident, pid, t_daemon, stack, ) log.info("Finished dumping stacks for process {0}.", pid) The provided code snippet includes necessary dependencies for implementing the `dump_after` function. Write a Python function `def dump_after(secs)` to solve the following problem: Invokes dump() on a background thread after waiting for the specified time. Here is the function: def dump_after(secs): """Invokes dump() on a background thread after waiting for the specified time.""" def dumper(): time.sleep(secs) try: dump() except: log.swallow_exception() thread = threading.Thread(target=dumper) thread.daemon = True thread.start()
Invokes dump() on a background thread after waiting for the specified time.
177,918
import time def reset(): global timestamp_zero timestamp_zero = time.monotonic()
null
177,919
import functools import threading def threadsafe_method(func): """Marks a method of a ThreadSafeSingleton-derived class as inherently thread-safe. A method so marked must either not use any singleton state, or lock it appropriately. """ func.is_threadsafe_method = True return func The provided code snippet includes necessary dependencies for implementing the `autolocked_method` function. Write a Python function `def autolocked_method(func)` to solve the following problem: Automatically synchronizes all calls of a method of a ThreadSafeSingleton-derived class by locking the singleton for the duration of each call. Here is the function: def autolocked_method(func): """Automatically synchronizes all calls of a method of a ThreadSafeSingleton-derived class by locking the singleton for the duration of each call. """ @functools.wraps(func) @threadsafe_method def lock_and_call(self, *args, **kwargs): with self: return func(self, *args, **kwargs) return lock_and_call
Automatically synchronizes all calls of a method of a ThreadSafeSingleton-derived class by locking the singleton for the duration of each call.
177,920
import socket import sys import threading from debugpy.common import log from debugpy.common.util import hide_thread_from_debugger def _new_sock(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # Set TCP keepalive on an open socket. # It activates after 1 second (TCP_KEEPIDLE,) of idleness, # then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL), # and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) except (AttributeError, OSError): pass # May not be available everywhere. try: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1) except (AttributeError, OSError): pass # May not be available everywhere. try: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) except (AttributeError, OSError): pass # May not be available everywhere. try: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) except (AttributeError, OSError): pass # May not be available everywhere. return sock The provided code snippet includes necessary dependencies for implementing the `create_client` function. Write a Python function `def create_client()` to solve the following problem: Return a client socket that may be connected to a remote address. Here is the function: def create_client(): """Return a client socket that may be connected to a remote address.""" return _new_sock()
Return a client socket that may be connected to a remote address.
177,921
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util _files = {} _levels = set() def _update_levels(): global _levels _levels = frozenset(level for file in _files.values() for level in file.levels)
null
177,922
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util _lock = threading.RLock() def write(level, text, _to_files=all): assert level in LEVELS t = timestamp.current() format_string = "{0}+{1:" + timestamp_format + "}: " prefix = format_string.format(level[0].upper(), t) text = getattr(_tls, "prefix", "") + text indent = "\n" + (" " * len(prefix)) output = indent.join(text.split("\n")) output = prefix + output + "\n\n" with _lock: if _to_files is all: _to_files = _files.values() for file in _to_files: file.write(level, output) return text stderr = LogFile( "<stderr>", sys.stderr, levels=os.getenv("DEBUGPY_LOG_STDERR", "warning error").split(), close_file=False, ) def newline(level="info"): with _lock: stderr.write(level, "\n")
null
177,923
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util _tls = threading.local() The provided code snippet includes necessary dependencies for implementing the `prefixed` function. Write a Python function `def prefixed(format_string, *args, **kwargs)` to solve the following problem: Adds a prefix to all messages logged from the current thread for the duration of the context manager. Here is the function: def prefixed(format_string, *args, **kwargs): """Adds a prefix to all messages logged from the current thread for the duration of the context manager. """ prefix = format_string.format(*args, **kwargs) old_prefix = getattr(_tls, "prefix", "") _tls.prefix = prefix + old_prefix try: yield finally: _tls.prefix = old_prefix
Adds a prefix to all messages logged from the current thread for the duration of the context manager.
177,924
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util _files = {} def _close_files(): for file in tuple(_files.values()): file.close()
null
177,925
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util warning = functools.partial(write_format, "warning") def _repr(value): # pragma: no cover warning("$REPR {0!r}", value)
null
177,926
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util warning = functools.partial(write_format, "warning") def _vars(*names): # pragma: no cover locals = inspect.currentframe().f_back.f_locals if names: locals = {name: locals[name] for name in names if name in locals} warning("$VARS {0!r}", locals)
null
177,927
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util warning = functools.partial(write_format, "warning") def _stack(): # pragma: no cover stack = "\n".join(traceback.format_stack()) warning("$STACK:\n\n{0}", stack)
null
177,928
import atexit import contextlib import functools import inspect import io import os import platform import sys import threading import traceback import debugpy from debugpy.common import json, timestamp, util warning = functools.partial(write_format, "warning") def _threads(): # pragma: no cover output = "\n".join([str(t) for t in threading.enumerate()]) warning("$THREADS:\n\n{0}", output)
null
177,929
import codecs import os import pydevd import socket import sys import threading import debugpy from debugpy import adapter from debugpy.common import json, log, sockets from _pydevd_bundle.pydevd_constants import get_global_debugger from pydevd_file_utils import absolute_path from debugpy.common.util import hide_debugpy_internals _config = { "qt": "none", "subProcess": True, "python": sys.executable, "pythonEnv": {}, } def _settrace(*args, **kwargs): log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs) # The stdin in notification is not acted upon in debugpy, so, disable it. kwargs.setdefault("notify_stdin", False) try: return pydevd.settrace(*args, **kwargs) except Exception: raise else: _settrace.called = True _settrace.called = False def ensure_logging(): """Starts logging to log.log_dir, if it hasn't already been done.""" if ensure_logging.ensured: return ensure_logging.ensured = True log.to_file(prefix="debugpy.server") log.describe_environment("Initial environment:") if log.log_dir is not None: pydevd.log_to(log.log_dir + "/debugpy.pydevd.log") ensure_logging.ensured = False import json def absolute_path(filename): ''' Provides a version of the filename that's absolute (and NOT normalized). ''' return get_abs_path_real_path_and_base_from_file(filename)[0] def hide_debugpy_internals(): """Returns True if the caller should hide something from debugpy.""" return "DEBUGPY_TRACE_DEBUGPY" not in os.environ def _starts_debugging(func): def debug(address, **kwargs): if _settrace.called: raise RuntimeError("this process already has a debug adapter") try: _, port = address except Exception: port = address address = ("127.0.0.1", port) try: port.__index__() # ensure it's int-like except Exception: raise ValueError("expected port or (host, port)") if not (0 <= port < 2 ** 16): raise ValueError("invalid port number") ensure_logging() log.debug("{0}({1!r}, **{2!r})", func.__name__, address, kwargs) log.info("Initial debug configuration: {0}", json.repr(_config)) qt_mode = _config.get("qt", "none") if qt_mode != "none": pydevd.enable_qt_support(qt_mode) settrace_kwargs = { "suspend": False, "patch_multiprocessing": _config.get("subProcess", True), } if hide_debugpy_internals(): debugpy_path = os.path.dirname(absolute_path(debugpy.__file__)) settrace_kwargs["dont_trace_start_patterns"] = (debugpy_path,) settrace_kwargs["dont_trace_end_patterns"] = (str("debugpy_launcher.py"),) try: return func(address, settrace_kwargs, **kwargs) except Exception: log.reraise_exception("{0}() failed:", func.__name__, level="info") return debug
null
177,930
import codecs import os import pydevd import socket import sys import threading import debugpy from debugpy import adapter from debugpy.common import json, log, sockets from _pydevd_bundle.pydevd_constants import get_global_debugger from pydevd_file_utils import absolute_path from debugpy.common.util import hide_debugpy_internals def _settrace(*args, **kwargs): log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs) # The stdin in notification is not acted upon in debugpy, so, disable it. kwargs.setdefault("notify_stdin", False) try: return pydevd.settrace(*args, **kwargs) except Exception: raise else: _settrace.called = True _settrace.called = False def ensure_logging(): """Starts logging to log.log_dir, if it hasn't already been done.""" if ensure_logging.ensured: return ensure_logging.ensured = True log.to_file(prefix="debugpy.server") log.describe_environment("Initial environment:") if log.log_dir is not None: pydevd.log_to(log.log_dir + "/debugpy.pydevd.log") ensure_logging.ensured = False def is_client_connected(): return pydevd._is_attached() import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def get_global_debugger(): return GlobalDebuggerHolder.global_dbg def breakpoint(): ensure_logging() if not is_client_connected(): log.info("breakpoint() ignored - debugger not attached") return log.debug("breakpoint()") # Get the first frame in the stack that's not an internal frame. pydb = get_global_debugger() stop_at_frame = sys._getframe().f_back while ( stop_at_frame is not None and pydb.get_file_type(stop_at_frame) == pydb.PYDEV_FILE ): stop_at_frame = stop_at_frame.f_back _settrace( suspend=True, trace_only_current_thread=True, patch_multiprocessing=False, stop_at_frame=stop_at_frame, ) stop_at_frame = None
null
177,931
import codecs import os import pydevd import socket import sys import threading import debugpy from debugpy import adapter from debugpy.common import json, log, sockets from _pydevd_bundle.pydevd_constants import get_global_debugger from pydevd_file_utils import absolute_path from debugpy.common.util import hide_debugpy_internals def _settrace(*args, **kwargs): log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs) # The stdin in notification is not acted upon in debugpy, so, disable it. kwargs.setdefault("notify_stdin", False) try: return pydevd.settrace(*args, **kwargs) except Exception: raise else: _settrace.called = True _settrace.called = False def ensure_logging(): """Starts logging to log.log_dir, if it hasn't already been done.""" if ensure_logging.ensured: return ensure_logging.ensured = True log.to_file(prefix="debugpy.server") log.describe_environment("Initial environment:") if log.log_dir is not None: pydevd.log_to(log.log_dir + "/debugpy.pydevd.log") ensure_logging.ensured = False def debug_this_thread(): ensure_logging() log.debug("debug_this_thread()") _settrace(suspend=False)
null
177,932
import codecs import os import pydevd import socket import sys import threading import debugpy from debugpy import adapter from debugpy.common import json, log, sockets from _pydevd_bundle.pydevd_constants import get_global_debugger from pydevd_file_utils import absolute_path from debugpy.common.util import hide_debugpy_internals def ensure_logging(): ensure_logging.ensured = False def get_global_debugger(): def trace_this_thread(should_trace): ensure_logging() log.debug("trace_this_thread({0!r})", should_trace) pydb = get_global_debugger() if should_trace: pydb.enable_tracing() else: pydb.disable_tracing()
null
177,933
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api def in_range(parser, start, stop): def parse(s): n = parser(s) if start is not None and n < start: raise ValueError("must be >= {0}".format(start)) if stop is not None and n >= stop: raise ValueError("must be < {0}".format(stop)) return n return parse
null
177,934
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api HELP = """debugpy {0} See https://aka.ms/debugpy for documentation. Usage: debugpy --listen | --connect [<host>:]<port> [--wait-for-client] [--configure-<name> <value>]... [--log-to <path>] [--log-to-stderr] {1} [<arg>]... """.format( debugpy.__version__, TARGET ) import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def print_help_and_exit(switch, it): print(HELP, file=sys.stderr) sys.exit(0)
null
177,935
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def print_version_and_exit(switch, it): print(debugpy.__version__) sys.exit(0)
null
177,936
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def set_arg(varname, parser=(lambda x: x)): def do(arg, it): value = parser(next(it)) setattr(options, varname, value) return do
null
177,937
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def set_const(varname, value): def do(arg, it): setattr(options, varname, value) return do
null
177,938
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def set_address(mode): def do(arg, it): if options.address is not None: raise ValueError("--listen and --connect are mutually exclusive") # It's either host:port, or just port. value = next(it) host, sep, port = value.partition(":") if not sep: host = "127.0.0.1" port = value try: port = int(port) except Exception: port = -1 if not (0 <= port < 2 ** 16): raise ValueError("invalid port number") options.mode = mode options.address = (host, port) return do
null
177,939
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def set_config(arg, it): prefix = "--configure-" assert arg.startswith(prefix) name = arg[len(prefix) :] value = next(it) if name not in options.config: raise ValueError("unknown property {0!r}".format(name)) expected_type = type(options.config[name]) try: if expected_type is bool: value = {"true": True, "false": False}[value.lower()] else: value = expected_type(value) except Exception: raise ValueError("{0!r} must be a {1}".format(name, expected_type.__name__)) options.config[name] = value
null
177,940
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def set_target(kind, parser=(lambda x: x), positional=False): def do(arg, it): options.target_kind = kind target = parser(arg if positional else next(it)) if isinstance(target, bytes): # target may be the code, so, try some additional encodings... try: target = target.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: try: target = target.decode("utf-8") except UnicodeDecodeError: import locale target = target.decode(locale.getpreferredencoding(False)) options.target = target return do
null
177,941
import json import os import re import sys from importlib.util import find_spec import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api TARGET = "<filename> | -m <module> | -c <code> | --pid <pid>" options = Options() options.config = {"qt": "none", "subProcess": True} switches = [ # Switch Placeholder Action # ====== =========== ====== # Switches that are documented for use by end users. ("-(\\?|h|-help)", None, print_help_and_exit), ("-(V|-version)", None, print_version_and_exit), ("--log-to" , "<path>", set_arg("log_to")), ("--log-to-stderr", None, set_const("log_to_stderr", True)), ("--listen", "<address>", set_address("listen")), ("--connect", "<address>", set_address("connect")), ("--wait-for-client", None, set_const("wait_for_client", True)), ("--configure-.+", "<value>", set_config), # Switches that are used internally by the client or debugpy itself. ("--adapter-access-token", "<token>", set_arg("adapter_access_token")), # Targets. The "" entry corresponds to positional command line arguments, # i.e. the ones not preceded by any switch name. ("", "<filename>", set_target("file", positional=True)), ("-m", "<module>", set_target("module")), ("-c", "<code>", set_target("code")), ("--pid", "<pid>", set_target("pid", pid)), ] def consume_argv(): def parse_argv(): seen = set() it = consume_argv() while True: try: arg = next(it) except StopIteration: raise ValueError("missing target: " + TARGET) switch = arg if not switch.startswith("-"): switch = "" for pattern, placeholder, action in switches: if re.match("^(" + pattern + ")$", switch): break else: raise ValueError("unrecognized switch " + switch) if switch in seen: raise ValueError("duplicate switch " + switch) else: seen.add(switch) try: action(arg, it) except StopIteration: assert placeholder is not None raise ValueError("{0}: missing {1}".format(switch, placeholder)) except Exception as exc: raise ValueError("invalid {0} {1}: {2}".format(switch, placeholder, exc)) if options.target is not None: break if options.mode is None: raise ValueError("either --listen or --connect is required") if options.adapter_access_token is not None and options.mode != "connect": raise ValueError("--adapter-access-token requires --connect") if options.target_kind == "pid" and options.wait_for_client: raise ValueError("--pid does not support --wait-for-client") assert options.target is not None assert options.target_kind is not None assert options.address is not None
null
177,942
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def start_debugging(argv_0): # We need to set up sys.argv[0] before invoking either listen() or connect(), # because they use it to report the "process" event. Thus, we can't rely on # run_path() and run_module() doing that, even though they will eventually. sys.argv[0] = argv_0 log.debug("sys.argv after patching: {0!r}", sys.argv) debugpy.configure(options.config) if options.mode == "listen": debugpy.listen(options.address) elif options.mode == "connect": debugpy.connect(options.address, access_token=options.adapter_access_token) else: raise AssertionError(repr(options.mode)) if options.wait_for_client: debugpy.wait_for_client() import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def run_file(): target = options.target start_debugging(target) # run_path has one difference with invoking Python from command-line: # if the target is a file (rather than a directory), it does not add its # parent directory to sys.path. Thus, importing other modules from the # same directory is broken unless sys.path is patched here. if os.path.isfile(target): dir = os.path.dirname(target) sys.path.insert(0, dir) else: log.debug("Not a file: {0!r}", target) log.describe_environment("Pre-launch environment:") log.info("Running file {0!r}", target) runpy.run_path(target, run_name="__main__")
null
177,943
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def start_debugging(argv_0): # We need to set up sys.argv[0] before invoking either listen() or connect(), # because they use it to report the "process" event. Thus, we can't rely on # run_path() and run_module() doing that, even though they will eventually. sys.argv[0] = argv_0 log.debug("sys.argv after patching: {0!r}", sys.argv) debugpy.configure(options.config) if options.mode == "listen": debugpy.listen(options.address) elif options.mode == "connect": debugpy.connect(options.address, access_token=options.adapter_access_token) else: raise AssertionError(repr(options.mode)) if options.wait_for_client: debugpy.wait_for_client() import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def run_module(): # Add current directory to path, like Python itself does for -m. This must # be in place before trying to use find_spec below to resolve submodules. sys.path.insert(0, str("")) # We want to do the same thing that run_module() would do here, without # actually invoking it. argv_0 = sys.argv[0] try: spec = find_spec(options.target) if spec is not None: argv_0 = spec.origin except Exception: log.swallow_exception("Error determining module path for sys.argv") start_debugging(argv_0) log.describe_environment("Pre-launch environment:") log.info("Running module {0!r}", options.target) # Docs say that runpy.run_module is equivalent to -m, but it's not actually # the case for packages - -m sets __name__ to "__main__", but run_module sets # it to "pkg.__main__". This breaks everything that uses the standard pattern # __name__ == "__main__" to detect being run as a CLI app. On the other hand, # runpy._run_module_as_main is a private function that actually implements -m. try: run_module_as_main = runpy._run_module_as_main except AttributeError: log.warning("runpy._run_module_as_main is missing, falling back to run_module.") runpy.run_module(options.target, alter_sys=True) else: run_module_as_main(options.target, alter_argv=True)
null
177,944
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} def start_debugging(argv_0): # We need to set up sys.argv[0] before invoking either listen() or connect(), # because they use it to report the "process" event. Thus, we can't rely on # run_path() and run_module() doing that, even though they will eventually. sys.argv[0] = argv_0 log.debug("sys.argv after patching: {0!r}", sys.argv) debugpy.configure(options.config) if options.mode == "listen": debugpy.listen(options.address) elif options.mode == "connect": debugpy.connect(options.address, access_token=options.adapter_access_token) else: raise AssertionError(repr(options.mode)) if options.wait_for_client: debugpy.wait_for_client() import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def run_code(): # Add current directory to path, like Python itself does for -c. sys.path.insert(0, str("")) code = compile(options.target, str("<string>"), str("exec")) start_debugging(str("-c")) log.describe_environment("Pre-launch environment:") log.info("Running code:\n\n{0}", options.target) eval(code, {})
null
177,945
import json import os import re import sys from importlib.util import find_spec assert "pydevd" in sys.modules import pydevd from _pydevd_bundle import pydevd_runpy as runpy import debugpy from debugpy.common import log from debugpy.server import api options = Options() options.config = {"qt": "none", "subProcess": True} pid = in_range(int, 0, None) import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads: bool # undocumented def attach_to_pid(): pid = options.target log.info("Attaching to process with PID={0}", pid) encode = lambda s: list(bytearray(s.encode("utf-8"))) if s is not None else None script_dir = os.path.dirname(debugpy.server.__file__) assert os.path.exists(script_dir) script_dir = encode(script_dir) setup = { "mode": options.mode, "address": options.address, "wait_for_client": options.wait_for_client, "log_to": options.log_to, "adapter_access_token": options.adapter_access_token, } setup = encode(json.dumps(setup)) python_code = """ import codecs; import json; import sys; decode = lambda s: codecs.utf_8_decode(bytearray(s))[0] if s is not None else None; script_dir = decode({script_dir}); setup = json.loads(decode({setup})); sys.path.insert(0, script_dir); import attach_pid_injected; del sys.path[0]; attach_pid_injected.attach(setup); """ python_code = ( python_code.replace("\r", "") .replace("\n", "") .format(script_dir=script_dir, setup=setup) ) log.info("Code to be injected: \n{0}", python_code.replace(";", ";\n")) # pydevd restriction on characters in injected code. assert not ( {'"', "'", "\r", "\n"} & set(python_code) ), "Injected code should not contain any single quotes, double quotes, or newlines." pydevd_attach_to_process_path = os.path.join( os.path.dirname(pydevd.__file__), "pydevd_attach_to_process" ) assert os.path.exists(pydevd_attach_to_process_path) sys.path.append(pydevd_attach_to_process_path) try: import add_code_to_python_process # noqa log.info("Injecting code into process with PID={0} ...", pid) add_code_to_python_process.run_python_code( pid, python_code, connect_debugger_tracing=True, show_debug_info=int(os.getenv("DEBUGPY_ATTACH_BY_PID_DEBUG_INFO", "0")), ) except Exception: log.reraise_exception("Code injection into PID={0} failed:", pid) log.info("Code injection into PID={0} completed.", pid)
null
177,946
import os _debugpy_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) import sys if sys.version_info >= (3, 7): from builtins import _PathLike if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): # undocumented import json def attach(setup): log = None try: import sys if "threading" not in sys.modules: try: def on_warn(msg): print(msg, file=sys.stderr) def on_exception(msg): print(msg, file=sys.stderr) def on_critical(msg): print(msg, file=sys.stderr) pydevd_attach_to_process_path = os.path.join( _debugpy_dir, "debugpy", "_vendored", "pydevd", "pydevd_attach_to_process", ) assert os.path.exists(pydevd_attach_to_process_path) sys.path.insert(0, pydevd_attach_to_process_path) # NOTE: that it's not a part of the pydevd PYTHONPATH import attach_script attach_script.fix_main_thread_id( on_warn=on_warn, on_exception=on_exception, on_critical=on_critical ) # NOTE: At this point it should be safe to remove this. sys.path.remove(pydevd_attach_to_process_path) except: import traceback traceback.print_exc() raise sys.path.insert(0, _debugpy_dir) try: import debugpy import debugpy.server from debugpy.common import json, log import pydevd finally: assert sys.path[0] == _debugpy_dir del sys.path[0] py_db = pydevd.get_global_debugger() if py_db is not None: py_db.dispose_and_kill_all_pydevd_threads(wait=False) if setup["log_to"] is not None: debugpy.log_to(setup["log_to"]) log.info("Configuring injected debugpy: {0}", json.repr(setup)) if setup["mode"] == "listen": debugpy.listen(setup["address"]) elif setup["mode"] == "connect": debugpy.connect( setup["address"], access_token=setup["adapter_access_token"] ) else: raise AssertionError(repr(setup)) except: import traceback traceback.print_exc() if log is None: raise else: log.reraise_exception() log.info("debugpy injected successfully")
null
177,947
import sys import locale import warnings def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where ``sys.std*`` might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. ``default`` is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding The provided code snippet includes necessary dependencies for implementing the `getdefaultencoding` function. Write a Python function `def getdefaultencoding(prefer_stream=True)` to solve the following problem: Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII on Python 2 or UTF8 on Python 3. Here is the function: def getdefaultencoding(prefer_stream=True): """Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII on Python 2 or UTF8 on Python 3. """ enc = None if prefer_stream: enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. if enc == 'cp0': warnings.warn( "Invalid code page cp0 detected - using cp1252 instead." "If cp1252 is incorrect please ensure a valid code page " "is defined for the process.", RuntimeWarning) return 'cp1252' return enc
Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII on Python 2 or UTF8 on Python 3.
177,948
import os import sys import errno import shutil import random from . import py3compat def expand_path(s): """Expand $VARS and ~names in a string, like a shell :Examples: In [2]: os.environ['FOO']='test' In [3]: expand_path('variable FOO is $FOO') Out[3]: 'variable FOO is test' """ # This is a pretty subtle hack. When expand user is given a UNC path # on Windows (\\server\share$\%username%), os.path.expandvars, removes # the $ to get (\\server\share\%username%). I think it considered $ # alone an empty var. But, we need the $ to remains there (it indicates # a hidden share). if os.name=='nt': s = s.replace('$\\', 'IPYTHON_TEMP') s = os.path.expandvars(os.path.expanduser(s)) if os.name=='nt': s = s.replace('IPYTHON_TEMP', '$\\') return s The provided code snippet includes necessary dependencies for implementing the `filefind` function. Write a Python function `def filefind(filename, path_dirs=None)` to solve the following problem: Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- Raises :exc:`IOError` or returns absolute path to file. Here is the function: def filefind(filename, path_dirs=None): """Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- Raises :exc:`IOError` or returns absolute path to file. """ # If paths are quoted, abspath gets confused, strip them... filename = filename.strip('"').strip("'") # If the input is an absolute path, just check it exists if os.path.isabs(filename) and os.path.isfile(filename): return filename if path_dirs is None: path_dirs = ("",) elif isinstance(path_dirs, py3compat.string_types): path_dirs = (path_dirs,) for path in path_dirs: if path == '.': path = py3compat.getcwd() testname = expand_path(os.path.join(path, filename)) if os.path.isfile(testname): return os.path.abspath(testname) raise IOError("File %r does not exist in any of the search paths: %r" % (filename, path_dirs) )
Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- Raises :exc:`IOError` or returns absolute path to file.
177,949
import os import sys import errno import shutil import random from . import py3compat def link(src, dst): """Hard links ``src`` to ``dst``, returning 0 or errno. Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't supported by the operating system. """ if not hasattr(os, "link"): return ENOLINK link_errno = 0 try: os.link(src, dst) except OSError as e: link_errno = e.errno return link_errno The provided code snippet includes necessary dependencies for implementing the `link_or_copy` function. Write a Python function `def link_or_copy(src, dst)` to solve the following problem: Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. Here is the function: def link_or_copy(src, dst): """Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) link_errno = link(src, dst) if link_errno == errno.EEXIST: if os.stat(src).st_ino == os.stat(dst).st_ino: # dst is already a hard link to the correct file, so we don't need # to do anything else. If we try to link and rename the file # anyway, we get duplicate files - see http://bugs.python.org/issue21876 return new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), ) try: link_or_copy(src, new_dst) except: try: os.remove(new_dst) except OSError: pass raise os.rename(new_dst, dst) elif link_errno != 0: # Either link isn't supported, or the filesystem doesn't support # linking, or 'src' and 'dst' are on different filesystems. shutil.copy(src, dst)
Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place.
177,950
import os import sys import errno import shutil import random from . import py3compat The provided code snippet includes necessary dependencies for implementing the `ensure_dir_exists` function. Write a Python function `def ensure_dir_exists(path, mode=0o755)` to solve the following problem: ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777. Here is the function: def ensure_dir_exists(path, mode=0o755): """ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777. """ if not os.path.exists(path): try: os.makedirs(path, mode=mode) except OSError as e: if e.errno != errno.EEXIST: raise elif not os.path.isdir(path): raise IOError("%r exists but is not a directory" % path)
ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777.
177,951
import os import re import sys import textwrap from string import Formatter The provided code snippet includes necessary dependencies for implementing the `indent` function. Write a Python function `def indent(instr,nspaces=4, ntabs=0, flatten=False)` to solve the following problem: Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces. Here is the function: def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces. """ if instr is None: return ind = '\t'*ntabs+' '*nspaces if flatten: pat = re.compile(r'^\s*', re.MULTILINE) else: pat = re.compile(r'^', re.MULTILINE) outstr = re.sub(pat, ind, instr) if outstr.endswith(os.linesep+ind): return outstr[:-len(ind)] else: return outstr
Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces.
177,952
import os import re import sys import textwrap from string import Formatter def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line return textwrap.dedent(text) # split first line splits = text.split('\n',1) if len(splits) == 1: # only one line return textwrap.dedent(text) first, rest = splits # dedent everything but the first line rest = textwrap.dedent(rest) return '\n'.join([first, rest]) The provided code snippet includes necessary dependencies for implementing the `wrap_paragraphs` function. Write a Python function `def wrap_paragraphs(text, ncols=80)` to solve the following problem: Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. Here is the function: def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) text = dedent(text).strip() paragraphs = paragraph_re.split(text)[::2] # every other entry is space out_ps = [] indent_re = re.compile(r'\n\s+', re.MULTILINE) for p in paragraphs: # presume indentation that survives dedent is meaningful formatting, # so don't fill unless text is flush. if indent_re.search(p) is None: # wrap paragraph p = textwrap.fill(p, ncols) out_ps.append(p) return out_ps
Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns.
177,953
import os import re import sys import textwrap from string import Formatter The provided code snippet includes necessary dependencies for implementing the `strip_ansi` function. Write a Python function `def strip_ansi(source)` to solve the following problem: Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from Here is the function: def strip_ansi(source): """ Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from """ return re.sub(r'\033\[(\d|;)+?m', '', source)
Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from
177,954
import os import re import sys import textwrap from string import Formatter def compute_item_matrix(items, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters ---------- items list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) How much caracters will be used as a separation between each columns. displaywidth : int (default=80) The width of the area onto wich the columns should enter Returns ------- strings_matrix nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as colums. If the total number of elements in `items` does not equal the product of rows*columns, the last element of some lists are filled with `None`. dict_info some info to make columnize easier: columns_numbers number of columns rows_numbers number of rows columns_width list of with of each columns optimal_separator_width best separator width between columns Examples -------- :: In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] ...: compute_item_matrix(l,displaywidth=12) Out[1]: ([['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]], {'columns_numbers': 3, 'columns_width': [5, 1, 1], 'optimal_separator_width': 2, 'rows_numbers': 5}) """ info = _find_optimal(list(map(len, items)), *args, **kwargs) nrow, ncol = info['rows_numbers'], info['columns_numbers'] return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info) The provided code snippet includes necessary dependencies for implementing the `columnize` function. Write a Python function `def columnize(items, separator=' ', displaywidth=80)` to solve the following problem: Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. Here is the function: def columnize(items, separator=' ', displaywidth=80): """ Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. """ if not items : return '\n' matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) return '\n'.join(map(sjoin, fmatrix))+'\n'
Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string.
177,955
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def no_code(x, encoding=None): return x
null
177,956
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `buffer_to_bytes` function. Write a Python function `def buffer_to_bytes(buf)` to solve the following problem: Cast a buffer or memoryview object to bytes Here is the function: def buffer_to_bytes(buf): """Cast a buffer or memoryview object to bytes""" if isinstance(buf, memoryview): return buf.tobytes() if not isinstance(buf, bytes): return bytes(buf) return buf
Cast a buffer or memoryview object to bytes
177,957
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def _modify_str_or_docstring(str_change_func): @functools.wraps(str_change_func) def wrapper(func_or_str): if isinstance(func_or_str, string_types): func = None doc = func_or_str else: func = func_or_str doc = func.__doc__ doc = str_change_func(doc) if func: func.__doc__ = doc return func return doc return wrapper
null
177,958
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `safe_unicode` function. Write a Python function `def safe_unicode(e)` to solve the following problem: unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. Here is the function: def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode_type(e) except UnicodeError: pass try: return str_to_unicode(str(e)) except UnicodeError: pass try: return str_to_unicode(repr(e)) except UnicodeError: pass return u'Unrecoverably corrupt evalue'
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
177,959
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform if sys.version_info[0] >= 3 or platform.python_implementation() == 'IronPython': str_to_unicode = no_code unicode_to_str = no_code str_to_bytes = encode bytes_to_str = decode cast_bytes_py2 = no_code cast_unicode_py2 = no_code buffer_to_bytes_py2 = no_code string_types = (str,) unicode_type = str else: str_to_unicode = decode unicode_to_str = encode str_to_bytes = no_code bytes_to_str = no_code cast_bytes_py2 = cast_bytes cast_unicode_py2 = cast_unicode buffer_to_bytes_py2 = buffer_to_bytes string_types = (str, unicode) unicode_type = unicode if sys.version_info[0] >= 3: PY3 = True # keep reference to builtin_mod because the kernel overrides that value # to forward requests to a frontend. builtin_mod_name = "builtins" import builtins as builtin_mod which = shutil.which xrange = range getcwd = os.getcwd MethodType = types.MethodType # Refactor print statements in doctests. _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) # Abstract u'abc' syntax: else: PY3 = False # keep reference to builtin_mod because the kernel overrides that value # to forward requests to a frontend. builtin_mod_name = "__builtin__" import __builtin__ as builtin_mod import re _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") xrange = xrange getcwd = os.getcwdu which = _shutil_which # Abstract u'abc' syntax: if sys.platform == 'win32': else: The provided code snippet includes necessary dependencies for implementing the `_shutil_which` function. Write a Python function `def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None)` to solve the following problem: Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. This is a backport of shutil.which from Python 3.4 Here is the function: def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. This is a backport of shutil.which from Python 3.4 """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes checking relative to the # current directory, e.g. ./script if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". # If it does match, only test that one, otherwise we have to try # others. if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if not normdir in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. This is a backport of shutil.which from Python 3.4
177,960
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def input(prompt=''): return builtin_mod.input(prompt)
null
177,961
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def isidentifier(s, dotted=False): if dotted: return all(isidentifier(a) for a in s.split(".")) return s.isidentifier()
null
177,962
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def iteritems(d): return iter(d.items())
null
177,963
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def itervalues(d): return iter(d.values())
null
177,964
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def execfile(fname, glob, loc=None, compiler=None): loc = loc if (loc is not None) else glob with open(fname, 'rb') as f: compiler = compiler or compile exec(compiler(f.read(), fname, 'exec'), glob, loc)
null
177,965
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform if sys.version_info[0] >= 3: PY3 = True # keep reference to builtin_mod because the kernel overrides that value # to forward requests to a frontend. builtin_mod_name = "builtins" import builtins as builtin_mod which = shutil.which xrange = range getcwd = os.getcwd MethodType = types.MethodType # Refactor print statements in doctests. _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) def _print_statement_sub(match): expr = match.groups('expr') return "print(%s)" % expr # Abstract u'abc' syntax: else: PY3 = False # keep reference to builtin_mod because the kernel overrides that value # to forward requests to a frontend. builtin_mod_name = "__builtin__" import __builtin__ as builtin_mod import re _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") xrange = xrange getcwd = os.getcwdu which = _shutil_which # Abstract u'abc' syntax: if sys.platform == 'win32': else: The provided code snippet includes necessary dependencies for implementing the `doctest_refactor_print` function. Write a Python function `def doctest_refactor_print(doc)` to solve the following problem: Refactor 'print x' statements in a doctest to print(x) style. 2to3 unfortunately doesn't pick up on our doctests. Can accept a string or a function, so it can be used as a decorator. Here is the function: def doctest_refactor_print(doc): """Refactor 'print x' statements in a doctest to print(x) style. 2to3 unfortunately doesn't pick up on our doctests. Can accept a string or a function, so it can be used as a decorator.""" return _print_statement_re.sub(_print_statement_sub, doc)
Refactor 'print x' statements in a doctest to print(x) style. 2to3 unfortunately doesn't pick up on our doctests. Can accept a string or a function, so it can be used as a decorator.
177,966
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `u_format` function. Write a Python function `def u_format(s)` to solve the following problem: {u}'abc'" --> "'abc'" (Python 3) Accepts a string or a function, so it can be used as a decorator. Here is the function: def u_format(s): """"{u}'abc'" --> "'abc'" (Python 3) Accepts a string or a function, so it can be used as a decorator.""" return s.format(u='')
{u}'abc'" --> "'abc'" (Python 3) Accepts a string or a function, so it can be used as a decorator.
177,967
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `get_closure` function. Write a Python function `def get_closure(f)` to solve the following problem: Get a function's closure attribute Here is the function: def get_closure(f): """Get a function's closure attribute""" return f.__closure__
Get a function's closure attribute
177,968
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def input(prompt=''): return builtin_mod.raw_input(prompt)
null
177,969
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def isidentifier(s, dotted=False): if dotted: return all(isidentifier(a) for a in s.split(".")) return bool(_name_re.match(s))
null
177,970
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def iteritems(d): return d.iteritems()
null
177,971
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def itervalues(d): return d.itervalues()
null
177,972
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def MethodType(func, instance): return types.MethodType(func, instance, type(instance))
null
177,973
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def doctest_refactor_print(func_or_str): return func_or_str
null