id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
177,773 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
class ReturnInfo(object):
def __init__(self, return_line):
self.return_line = return_line
def __str__(self):
return '{return: %s}' % (self.return_line,)
__repr__ = __str__
def _get_line(op_offset_to_line, op_offset, firstlineno, search=False):
op_offset_original = op_offset
while op_offset >= 0:
ret = op_offset_to_line.get(op_offset)
if ret is not None:
return ret - firstlineno
if not search:
return ret
else:
op_offset -= 1
raise AssertionError('Unable to find line for offset: %s.Info: %s' % (
op_offset_original, op_offset_to_line))
def iter_instructions(co):
if sys.version_info[0] < 3:
iter_in = _iter_as_bytecode_as_instructions_py2(co)
else:
iter_in = dis.Bytecode(co)
iter_in = list(iter_in)
bytecode_to_instruction = {}
for instruction in iter_in:
bytecode_to_instruction[instruction.offset] = instruction
if iter_in:
for instruction in iter_in:
yield instruction
import ast as ast_module
opname: List[str]
def collect_return_info(co, use_func_first_line=False):
if not hasattr(co, 'co_lnotab'):
return []
if use_func_first_line:
firstlineno = co.co_firstlineno
else:
firstlineno = 0
lst = []
op_offset_to_line = dict(dis.findlinestarts(co))
for instruction in iter_instructions(co):
curr_op_name = instruction.opname
if curr_op_name == 'RETURN_VALUE':
lst.append(ReturnInfo(_get_line(op_offset_to_line, instruction.offset, firstlineno, search=True)))
return lst | null |
177,774 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
class TryExceptInfo(object):
def __init__(self, try_line, ignore=False):
def is_line_in_try_block(self, line):
def is_line_in_except_block(self, line):
def __str__(self):
def _get_line(op_offset_to_line, op_offset, firstlineno, search=False):
def iter_instructions(co):
if sys.version_info[:2] <= (3, 9):
def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx):
elif sys.version_info[:2] == (3, 10):
def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx):
elif sys.version_info[:2] >= (3, 11):
import ast as ast_module
opname: List[str]
def collect_try_except_info(co, use_func_first_line=False):
# We no longer have 'END_FINALLY', so, we need to do things differently in Python 3.9
if not hasattr(co, 'co_lnotab'):
return []
if use_func_first_line:
firstlineno = co.co_firstlineno
else:
firstlineno = 0
try_except_info_lst = []
op_offset_to_line = dict(dis.findlinestarts(co))
offset_to_instruction_idx = {}
instructions = list(iter_instructions(co))
for i, instruction in enumerate(instructions):
offset_to_instruction_idx[instruction.offset] = i
for i, instruction in enumerate(instructions):
curr_op_name = instruction.opname
if curr_op_name in ('SETUP_FINALLY', 'SETUP_EXCEPT'): # SETUP_EXCEPT before Python 3.8, SETUP_FINALLY Python 3.8 onwards.
exception_end_instruction_index = offset_to_instruction_idx[instruction.argval]
jump_instruction = instructions[exception_end_instruction_index - 1]
if jump_instruction.opname not in ('JUMP_FORWARD', 'JUMP_ABSOLUTE'):
continue
except_end_instruction = None
indexes_checked = set()
indexes_checked.add(exception_end_instruction_index)
target_info = _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx)
while target_info is not None:
# Handle a try..except..except..except.
jump_instruction = target_info.jump_if_not_exc_instruction
except_end_instruction = target_info.except_end_instruction
if jump_instruction is not None:
check_index = offset_to_instruction_idx[jump_instruction.argval]
if check_index in indexes_checked:
break
indexes_checked.add(check_index)
target_info = _get_except_target_info(instructions, check_index, offset_to_instruction_idx)
else:
break
if except_end_instruction is not None:
try_except_info = TryExceptInfo(
_get_line(op_offset_to_line, instruction.offset, firstlineno, search=True),
ignore=False
)
try_except_info.except_bytecode_offset = instruction.argval
try_except_info.except_line = _get_line(
op_offset_to_line,
try_except_info.except_bytecode_offset,
firstlineno,
search=True
)
try_except_info.except_end_bytecode_offset = except_end_instruction.offset
try_except_info.except_end_line = _get_line(op_offset_to_line, except_end_instruction.offset, firstlineno, search=True)
try_except_info_lst.append(try_except_info)
for raise_instruction in instructions[i:offset_to_instruction_idx[try_except_info.except_end_bytecode_offset]]:
if raise_instruction.opname == 'RAISE_VARARGS':
if raise_instruction.argval == 0:
try_except_info.raise_lines_in_except.append(
_get_line(op_offset_to_line, raise_instruction.offset, firstlineno, search=True))
return try_except_info_lst | null |
177,775 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
class TryExceptInfo(object):
def __init__(self, try_line, ignore=False):
'''
:param try_line:
:param ignore:
Usually we should ignore any block that's not a try..except
(this can happen for finally blocks, with statements, etc, for
which we create temporary entries).
'''
self.try_line = try_line
self.ignore = ignore
self.except_line = -1
self.except_end_line = -1
self.raise_lines_in_except = []
# Note: these may not be available if generated from source instead of bytecode.
self.except_bytecode_offset = -1
self.except_end_bytecode_offset = -1
def is_line_in_try_block(self, line):
return self.try_line <= line < self.except_line
def is_line_in_except_block(self, line):
return self.except_line <= line <= self.except_end_line
def __str__(self):
lst = [
'{try:',
str(self.try_line),
' except ',
str(self.except_line),
' end block ',
str(self.except_end_line),
]
if self.raise_lines_in_except:
lst.append(' raises: %s' % (', '.join(str(x) for x in self.raise_lines_in_except),))
lst.append('}')
return ''.join(lst)
__repr__ = __str__
def _get_line(op_offset_to_line, op_offset, firstlineno, search=False):
op_offset_original = op_offset
while op_offset >= 0:
ret = op_offset_to_line.get(op_offset)
if ret is not None:
return ret - firstlineno
if not search:
return ret
else:
op_offset -= 1
raise AssertionError('Unable to find line for offset: %s.Info: %s' % (
op_offset_original, op_offset_to_line))
def iter_instructions(co):
if sys.version_info[0] < 3:
iter_in = _iter_as_bytecode_as_instructions_py2(co)
else:
iter_in = dis.Bytecode(co)
iter_in = list(iter_in)
bytecode_to_instruction = {}
for instruction in iter_in:
bytecode_to_instruction[instruction.offset] = instruction
if iter_in:
for instruction in iter_in:
yield instruction
if sys.version_info[:2] <= (3, 9):
def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx):
next_3 = [j_instruction.opname for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]]
# print('next_3:', [(j_instruction.opname, j_instruction.argval) for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]])
if next_3 == ['POP_TOP', 'POP_TOP', 'POP_TOP']: # try..except without checking exception.
try:
jump_instruction = instructions[exception_end_instruction_index - 1]
if jump_instruction.opname not in ('JUMP_FORWARD', 'JUMP_ABSOLUTE'):
return None
except IndexError:
pass
if jump_instruction.opname == 'JUMP_ABSOLUTE':
# On latest versions of Python 3 the interpreter has a go-backwards step,
# used to show the initial line of a for/while, etc (which is this
# JUMP_ABSOLUTE)... we're not really interested in it, but rather on where
# it points to.
except_end_instruction = instructions[offset_to_instruction_idx[jump_instruction.argval]]
idx = offset_to_instruction_idx[except_end_instruction.argval]
# Search for the POP_EXCEPT which should be at the end of the block.
for pop_except_instruction in reversed(instructions[:idx]):
if pop_except_instruction.opname == 'POP_EXCEPT':
except_end_instruction = pop_except_instruction
return _TargetInfo(except_end_instruction)
else:
return None # i.e.: Continue outer loop
else:
# JUMP_FORWARD
i = offset_to_instruction_idx[jump_instruction.argval]
try:
# i.e.: the jump is to the instruction after the block finishes (so, we need to
# get the previous instruction as that should be the place where the exception
# block finishes).
except_end_instruction = instructions[i - 1]
except:
pydev_log.critical('Error when computing try..except block end.')
return None
return _TargetInfo(except_end_instruction)
elif next_3 and next_3[0] == 'DUP_TOP': # try..except AssertionError.
iter_in = instructions[exception_end_instruction_index + 1:]
for j, jump_if_not_exc_instruction in enumerate(iter_in):
if jump_if_not_exc_instruction.opname == 'JUMP_IF_NOT_EXC_MATCH':
# Python 3.9
except_end_instruction = instructions[offset_to_instruction_idx[jump_if_not_exc_instruction.argval]]
return _TargetInfo(except_end_instruction, jump_if_not_exc_instruction)
elif jump_if_not_exc_instruction.opname == 'COMPARE_OP' and jump_if_not_exc_instruction.argval == 'exception match':
# Python 3.8 and before
try:
next_instruction = iter_in[j + 1]
except:
continue
if next_instruction.opname == 'POP_JUMP_IF_FALSE':
except_end_instruction = instructions[offset_to_instruction_idx[next_instruction.argval]]
return _TargetInfo(except_end_instruction, next_instruction)
else:
return None # i.e.: Continue outer loop
else:
# i.e.: we're not interested in try..finally statements, only try..except.
return None
elif sys.version_info[:2] == (3, 10):
def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx):
next_3 = [j_instruction.opname for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]]
# print('next_3:', [(j_instruction.opname, j_instruction.argval) for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]])
if next_3 == ['POP_TOP', 'POP_TOP', 'POP_TOP']: # try..except without checking exception.
# Previously there was a jump which was able to point where the exception would end. This
# is no longer true, now a bare except doesn't really have any indication in the bytecode
# where the end would be expected if the exception wasn't raised, so, we just blindly
# search for a POP_EXCEPT from the current position.
for pop_except_instruction in instructions[exception_end_instruction_index + 3:]:
if pop_except_instruction.opname == 'POP_EXCEPT':
except_end_instruction = pop_except_instruction
return _TargetInfo(except_end_instruction)
elif next_3 and next_3[0] == 'DUP_TOP': # try..except AssertionError.
iter_in = instructions[exception_end_instruction_index + 1:]
for jump_if_not_exc_instruction in iter_in:
if jump_if_not_exc_instruction.opname == 'JUMP_IF_NOT_EXC_MATCH':
# Python 3.9
except_end_instruction = instructions[offset_to_instruction_idx[jump_if_not_exc_instruction.argval]]
return _TargetInfo(except_end_instruction, jump_if_not_exc_instruction)
else:
return None # i.e.: Continue outer loop
else:
# i.e.: we're not interested in try..finally statements, only try..except.
return None
elif sys.version_info[:2] >= (3, 11):
import ast as ast_module
opname: List[str]
def collect_try_except_info(co, use_func_first_line=False):
# We no longer have 'END_FINALLY', so, we need to do things differently in Python 3.9
if not hasattr(co, 'co_lnotab'):
return []
if use_func_first_line:
firstlineno = co.co_firstlineno
else:
firstlineno = 0
try_except_info_lst = []
op_offset_to_line = dict(dis.findlinestarts(co))
offset_to_instruction_idx = {}
instructions = list(iter_instructions(co))
for i, instruction in enumerate(instructions):
offset_to_instruction_idx[instruction.offset] = i
for i, instruction in enumerate(instructions):
curr_op_name = instruction.opname
if curr_op_name == 'SETUP_FINALLY':
exception_end_instruction_index = offset_to_instruction_idx[instruction.argval]
jump_instruction = instructions[exception_end_instruction_index]
if jump_instruction.opname != 'DUP_TOP':
continue
except_end_instruction = None
indexes_checked = set()
indexes_checked.add(exception_end_instruction_index)
target_info = _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx)
while target_info is not None:
# Handle a try..except..except..except.
jump_instruction = target_info.jump_if_not_exc_instruction
except_end_instruction = target_info.except_end_instruction
if jump_instruction is not None:
check_index = offset_to_instruction_idx[jump_instruction.argval]
if check_index in indexes_checked:
break
indexes_checked.add(check_index)
target_info = _get_except_target_info(instructions, check_index, offset_to_instruction_idx)
else:
break
if except_end_instruction is not None:
try_except_info = TryExceptInfo(
_get_line(op_offset_to_line, instruction.offset, firstlineno, search=True),
ignore=False
)
try_except_info.except_bytecode_offset = instruction.argval
try_except_info.except_line = _get_line(
op_offset_to_line,
try_except_info.except_bytecode_offset,
firstlineno,
search=True
)
try_except_info.except_end_bytecode_offset = except_end_instruction.offset
# On Python 3.10 the final line of the except end isn't really correct, rather,
# it's engineered to be the same line of the except and not the end line of the
# block, so, the approach taken is to search for the biggest line between the
# except and the end instruction
except_end_line = -1
start_i = offset_to_instruction_idx[try_except_info.except_bytecode_offset]
end_i = offset_to_instruction_idx[except_end_instruction.offset]
for instruction in instructions[start_i: end_i + 1]:
found_at_line = op_offset_to_line.get(instruction.offset)
if found_at_line is not None and found_at_line > except_end_line:
except_end_line = found_at_line
try_except_info.except_end_line = except_end_line - firstlineno
try_except_info_lst.append(try_except_info)
for raise_instruction in instructions[i:offset_to_instruction_idx[try_except_info.except_end_bytecode_offset]]:
if raise_instruction.opname == 'RAISE_VARARGS':
if raise_instruction.argval == 0:
try_except_info.raise_lines_in_except.append(
_get_line(op_offset_to_line, raise_instruction.offset, firstlineno, search=True))
return try_except_info_lst | null |
177,776 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
import ast as ast_module
The provided code snippet includes necessary dependencies for implementing the `collect_try_except_info` function. Write a Python function `def collect_try_except_info(co, use_func_first_line=False)` to solve the following problem:
Note: if the filename is available and we can get the source, `collect_try_except_info_from_source` is preferred (this is kept as a fallback for cases where sources aren't available).
Here is the function:
def collect_try_except_info(co, use_func_first_line=False):
'''
Note: if the filename is available and we can get the source,
`collect_try_except_info_from_source` is preferred (this is kept as
a fallback for cases where sources aren't available).
'''
return [] | Note: if the filename is available and we can get the source, `collect_try_except_info_from_source` is preferred (this is kept as a fallback for cases where sources aren't available). |
177,777 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
import ast as ast_module
def collect_try_except_info_from_contents(contents, filename='<unknown>'):
ast = ast_module.parse(contents, filename)
visitor = _Visitor()
visitor.visit(ast)
return visitor.try_except_infos
def collect_try_except_info_from_source(filename):
with open(filename, 'rb') as stream:
contents = stream.read()
return collect_try_except_info_from_contents(contents, filename) | null |
177,778 | import dis
import inspect
import sys
from collections import namedtuple
from _pydev_bundle import pydev_log
from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst,
hasfree, hasjrel, haslocal, hasname, opname)
from io import StringIO
import ast as ast_module
class _Disassembler(object):
def __init__(self, co, firstlineno, level=0):
self.co = co
self.firstlineno = firstlineno
self.level = level
self.instructions = list(iter_instructions(co))
op_offset_to_line = self.op_offset_to_line = dict(dis.findlinestarts(co))
# Update offsets so that all offsets have the line index (and update it based on
# the passed firstlineno).
line_index = co.co_firstlineno - firstlineno
for instruction in self.instructions:
new_line_index = op_offset_to_line.get(instruction.offset)
if new_line_index is not None:
line_index = new_line_index - firstlineno
op_offset_to_line[instruction.offset] = line_index
else:
op_offset_to_line[instruction.offset] = line_index
BIG_LINE_INT = 9999999
SMALL_LINE_INT = -1
def min_line(self, *args):
m = self.BIG_LINE_INT
for arg in args:
if isinstance(arg, (list, tuple)):
m = min(m, self.min_line(*arg))
elif isinstance(arg, _MsgPart):
m = min(m, arg.line)
elif hasattr(arg, 'offset'):
m = min(m, self.op_offset_to_line[arg.offset])
return m
def max_line(self, *args):
m = self.SMALL_LINE_INT
for arg in args:
if isinstance(arg, (list, tuple)):
m = max(m, self.max_line(*arg))
elif isinstance(arg, _MsgPart):
m = max(m, arg.line)
elif hasattr(arg, 'offset'):
m = max(m, self.op_offset_to_line[arg.offset])
return m
def _lookahead(self):
'''
This handles and converts some common constructs from bytecode to actual source code.
It may change the list of instructions.
'''
msg = self._create_msg_part
found = []
fullrepr = None
# Collect all the load instructions
for next_instruction in self.instructions:
if next_instruction.opname in ('LOAD_GLOBAL', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_NAME'):
found.append(next_instruction)
else:
break
if not found:
return None
if next_instruction.opname == 'LOAD_ATTR':
prev_instruction = found[-1]
# Remove the current LOAD_ATTR
assert self.instructions.pop(len(found)) is next_instruction
# Add the LOAD_ATTR to the previous LOAD
self.instructions[len(found) - 1] = _Instruction(
prev_instruction.opname,
prev_instruction.opcode,
prev_instruction.starts_line,
prev_instruction.argval,
False, # prev_instruction.is_jump_target,
prev_instruction.offset,
(
msg(prev_instruction),
msg(prev_instruction, '.'),
msg(next_instruction)
),
)
return RESTART_FROM_LOOKAHEAD
if next_instruction.opname in ('CALL_FUNCTION', 'PRECALL'):
if len(found) == next_instruction.argval + 1:
force_restart = False
delta = 0
else:
force_restart = True
if len(found) > next_instruction.argval + 1:
delta = len(found) - (next_instruction.argval + 1)
else:
return None # This is odd
del_upto = delta + next_instruction.argval + 2 # +2 = NAME / CALL_FUNCTION
if next_instruction.opname == 'PRECALL':
del_upto += 1 # Also remove the CALL right after the PRECALL.
del self.instructions[delta:del_upto]
found = iter(found[delta:])
call_func = next(found)
args = list(found)
fullrepr = [
msg(call_func),
msg(call_func, '('),
]
prev = call_func
for i, arg in enumerate(args):
if i > 0:
fullrepr.append(msg(prev, ', '))
prev = arg
fullrepr.append(msg(arg))
fullrepr.append(msg(prev, ')'))
if force_restart:
self.instructions.insert(delta, _Instruction(
call_func.opname,
call_func.opcode,
call_func.starts_line,
call_func.argval,
False, # call_func.is_jump_target,
call_func.offset,
tuple(fullrepr),
))
return RESTART_FROM_LOOKAHEAD
elif next_instruction.opname == 'BUILD_TUPLE':
if len(found) == next_instruction.argval:
force_restart = False
delta = 0
else:
force_restart = True
if len(found) > next_instruction.argval:
delta = len(found) - (next_instruction.argval)
else:
return None # This is odd
del self.instructions[delta:delta + next_instruction.argval + 1] # +1 = BUILD_TUPLE
found = iter(found[delta:])
args = [instruction for instruction in found]
if args:
first_instruction = args[0]
else:
first_instruction = next_instruction
prev = first_instruction
fullrepr = []
fullrepr.append(msg(prev, '('))
for i, arg in enumerate(args):
if i > 0:
fullrepr.append(msg(prev, ', '))
prev = arg
fullrepr.append(msg(arg))
fullrepr.append(msg(prev, ')'))
if force_restart:
self.instructions.insert(delta, _Instruction(
first_instruction.opname,
first_instruction.opcode,
first_instruction.starts_line,
first_instruction.argval,
False, # first_instruction.is_jump_target,
first_instruction.offset,
tuple(fullrepr),
))
return RESTART_FROM_LOOKAHEAD
if fullrepr is not None and self.instructions:
if self.instructions[0].opname == 'POP_TOP':
self.instructions.pop(0)
if self.instructions[0].opname in ('STORE_FAST', 'STORE_NAME'):
next_instruction = self.instructions.pop(0)
return msg(next_instruction), msg(next_instruction, ' = '), fullrepr
if self.instructions[0].opname == 'RETURN_VALUE':
next_instruction = self.instructions.pop(0)
return msg(next_instruction, 'return ', line=self.min_line(next_instruction, fullrepr)), fullrepr
return fullrepr
def _decorate_jump_target(self, instruction, instruction_repr):
if instruction.is_jump_target:
return ('|', str(instruction.offset), '|', instruction_repr)
return instruction_repr
def _create_msg_part(self, instruction, tok=None, line=None):
dec = self._decorate_jump_target
if line is None or line in (self.BIG_LINE_INT, self.SMALL_LINE_INT):
line = self.op_offset_to_line[instruction.offset]
argrepr = instruction.argrepr
if isinstance(argrepr, str) and argrepr.startswith('NULL + '):
argrepr = argrepr[7:]
return _MsgPart(
line, tok if tok is not None else dec(instruction, argrepr))
def _next_instruction_to_str(self, line_to_contents):
# indent = ''
# if self.level > 0:
# indent += ' ' * self.level
# print(indent, 'handle', self.instructions[0])
if self.instructions:
ret = self._lookahead()
if ret:
return ret
msg = self._create_msg_part
instruction = self.instructions.pop(0)
if instruction.opname in 'RESUME':
return None
if instruction.opname in ('LOAD_GLOBAL', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_NAME'):
next_instruction = self.instructions[0]
if next_instruction.opname in ('STORE_FAST', 'STORE_NAME'):
self.instructions.pop(0)
return (
msg(next_instruction),
msg(next_instruction, ' = '),
msg(instruction))
if next_instruction.opname == 'RETURN_VALUE':
self.instructions.pop(0)
return (msg(instruction, 'return ', line=self.min_line(instruction)), msg(instruction))
if next_instruction.opname == 'RAISE_VARARGS' and next_instruction.argval == 1:
self.instructions.pop(0)
return (msg(instruction, 'raise ', line=self.min_line(instruction)), msg(instruction))
if instruction.opname == 'LOAD_CONST':
if inspect.iscode(instruction.argval):
code_line_to_contents = _Disassembler(
instruction.argval, self.firstlineno, self.level + 1
).build_line_to_contents()
for contents in code_line_to_contents.values():
contents.insert(0, ' ')
for line, contents in code_line_to_contents.items():
line_to_contents.setdefault(line, []).extend(contents)
return msg(instruction, 'LOAD_CONST(code)')
if instruction.opname == 'RAISE_VARARGS':
if instruction.argval == 0:
return msg(instruction, 'raise')
if instruction.opname == 'SETUP_FINALLY':
return msg(instruction, ('try(', instruction.argrepr, '):'))
if instruction.argrepr:
return msg(instruction, (instruction.opname, '(', instruction.argrepr, ')'))
if instruction.argval:
return msg(instruction, '%s{%s}' % (instruction.opname, instruction.argval,))
return msg(instruction, instruction.opname)
def build_line_to_contents(self):
# print('----')
# for instruction in self.instructions:
# print(instruction)
# print('----\n\n')
line_to_contents = {}
instructions = self.instructions
while instructions:
s = self._next_instruction_to_str(line_to_contents)
if s is RESTART_FROM_LOOKAHEAD:
continue
if s is None:
continue
_MsgPart.add_to_line_to_contents(s, line_to_contents)
m = self.max_line(s)
if m != self.SMALL_LINE_INT:
line_to_contents.setdefault(m, []).append(SEPARATOR)
return line_to_contents
def disassemble(self):
line_to_contents = self.build_line_to_contents()
stream = StringIO()
last_line = 0
show_lines = False
for line, contents in sorted(line_to_contents.items()):
while last_line < line - 1:
if show_lines:
stream.write('%s.\n' % (last_line + 1,))
else:
stream.write('\n')
last_line += 1
if show_lines:
stream.write('%s. ' % (line,))
for i, content in enumerate(contents):
if content == SEPARATOR:
if i != len(contents) - 1:
stream.write(', ')
else:
stream.write(content)
stream.write('\n')
last_line = line
return stream.getvalue()
The provided code snippet includes necessary dependencies for implementing the `code_to_bytecode_representation` function. Write a Python function `def code_to_bytecode_representation(co, use_func_first_line=False)` to solve the following problem:
A simple disassemble of bytecode. It does not attempt to provide the full Python source code, rather, it provides a low-level representation of the bytecode, respecting the lines (so, its target is making the bytecode easier to grasp and not providing the original source code). Note that it does show jump locations/targets and converts some common bytecode constructs to Python code to make it a bit easier to understand.
Here is the function:
def code_to_bytecode_representation(co, use_func_first_line=False):
'''
A simple disassemble of bytecode.
It does not attempt to provide the full Python source code, rather, it provides a low-level
representation of the bytecode, respecting the lines (so, its target is making the bytecode
easier to grasp and not providing the original source code).
Note that it does show jump locations/targets and converts some common bytecode constructs to
Python code to make it a bit easier to understand.
'''
# Reference for bytecodes:
# https://docs.python.org/3/library/dis.html
if use_func_first_line:
firstlineno = co.co_firstlineno
else:
firstlineno = 0
return _Disassembler(co, firstlineno).disassemble() | A simple disassemble of bytecode. It does not attempt to provide the full Python source code, rather, it provides a low-level representation of the bytecode, respecting the lines (so, its target is making the bytecode easier to grasp and not providing the original source code). Note that it does show jump locations/targets and converts some common bytecode constructs to Python code to make it a bit easier to understand. |
177,779 | from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle import _pydev_saved_modules
from _pydevd_bundle.pydevd_utils import notify_about_gevent_if_needed
import weakref
from _pydevd_bundle.pydevd_constants import IS_JYTHON, IS_IRONPYTHON, \
PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS
from _pydev_bundle.pydev_log import exception as pydev_log_exception
import sys
from _pydev_bundle import pydev_log
import pydevd_tracing
from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions
class PyDBDaemonThread(threading.Thread):
def __init__(self, py_db, target_and_args=None):
'''
:param target_and_args:
tuple(func, args, kwargs) if this should be a function and args to run.
-- Note: use through run_as_pydevd_daemon_thread().
'''
threading.Thread.__init__(self)
notify_about_gevent_if_needed()
self._py_db = weakref.ref(py_db)
self._kill_received = False
mark_as_pydevd_daemon_thread(self)
self._target_and_args = target_and_args
def py_db(self):
return self._py_db()
def run(self):
created_pydb_daemon = self.py_db.created_pydb_daemon_threads
created_pydb_daemon[self] = 1
try:
try:
if IS_JYTHON and not isinstance(threading.current_thread(), threading._MainThread):
# we shouldn't update sys.modules for the main thread, cause it leads to the second importing 'threading'
# module, and the new instance of main thread is created
ss = JyCore.PySystemState()
# Note: Py.setSystemState() affects only the current thread.
JyCore.Py.setSystemState(ss)
self._stop_trace()
self._on_run()
except:
if sys is not None and pydev_log_exception is not None:
pydev_log_exception()
finally:
del created_pydb_daemon[self]
def _on_run(self):
if self._target_and_args is not None:
target, args, kwargs = self._target_and_args
target(*args, **kwargs)
else:
raise NotImplementedError('Should be reimplemented by: %s' % self.__class__)
def do_kill_pydev_thread(self):
if not self._kill_received:
pydev_log.debug('%s received kill signal', self.name)
self._kill_received = True
def _stop_trace(self):
if self.pydev_do_not_trace:
pydevd_tracing.SetTrace(None) # no debugging on this thread
The provided code snippet includes necessary dependencies for implementing the `run_as_pydevd_daemon_thread` function. Write a Python function `def run_as_pydevd_daemon_thread(py_db, func, *args, **kwargs)` to solve the following problem:
Runs a function as a pydevd daemon thread (without any tracing in place).
Here is the function:
def run_as_pydevd_daemon_thread(py_db, func, *args, **kwargs):
'''
Runs a function as a pydevd daemon thread (without any tracing in place).
'''
t = PyDBDaemonThread(py_db, target_and_args=(func, args, kwargs))
t.name = '%s (pydevd daemon thread)' % (func.__name__,)
t.start()
return t | Runs a function as a pydevd daemon thread (without any tracing in place). |
177,780 | from _pydev_bundle import pydev_log
from types import CodeType
from _pydevd_frame_eval.vendored.bytecode.instr import _Variable
from _pydevd_frame_eval.vendored import bytecode
from _pydevd_frame_eval.vendored.bytecode import cfg as bytecode_cfg
import dis
import opcode as _opcode
from _pydevd_bundle.pydevd_constants import KeyifyList, DebugInfoHolder, IS_PY311_OR_GREATER
from bisect import bisect
from collections import deque
class KeyifyList(object):
def __init__(self, inner, key):
self.inner = inner
self.key = key
def __len__(self):
return len(self.inner)
def __getitem__(self, k):
return self.key(self.inner[k])
bisect = bisect_right
The provided code snippet includes necessary dependencies for implementing the `get_smart_step_into_variant_from_frame_offset` function. Write a Python function `def get_smart_step_into_variant_from_frame_offset(frame_f_lasti, variants)` to solve the following problem:
Given the frame.f_lasti, return the related `Variant`. :note: if the offset is found before any variant available or no variants are available, None is returned. :rtype: Variant|NoneType
Here is the function:
def get_smart_step_into_variant_from_frame_offset(frame_f_lasti, variants):
"""
Given the frame.f_lasti, return the related `Variant`.
:note: if the offset is found before any variant available or no variants are
available, None is returned.
:rtype: Variant|NoneType
"""
if not variants:
return None
i = bisect(KeyifyList(variants, lambda entry:entry.offset), frame_f_lasti)
if i == 0:
return None
else:
return variants[i - 1] | Given the frame.f_lasti, return the related `Variant`. :note: if the offset is found before any variant available or no variants are available, None is returned. :rtype: Variant|NoneType |
177,781 | import sys
import bisect
import types
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_utils, pydevd_source_mapping
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_comm import (InternalGetThreadStack, internal_get_completions,
InternalSetNextStatementThread, internal_reload_code,
InternalGetVariable, InternalGetArray, InternalLoadFullValue,
internal_get_description, internal_get_frame, internal_evaluate_expression, InternalConsoleExec,
internal_get_variable_json, internal_change_variable, internal_change_variable_json,
internal_evaluate_expression_json, internal_set_expression_json, internal_get_exception_details_json,
internal_step_in_thread, internal_smart_step_into)
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, file_system_encoding,
CMD_STEP_INTO_MY_CODE, CMD_STOP_ON_START, CMD_SMART_STEP_INTO)
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, set_protocol, get_protocol,
HTTP_JSON_PROTOCOL, JSON_PROTOCOL, DebugInfoHolder, IS_WINDOWS)
from _pydevd_bundle.pydevd_net_command_factory_json import NetCommandFactoryJson
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
import pydevd_file_utils
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint
from pydevd_tracing import get_exception_traceback_str
import os
import subprocess
import ctypes
from _pydevd_bundle.pydevd_collect_bytecode_info import code_to_bytecode_representation
import itertools
import linecache
from _pydevd_bundle.pydevd_utils import DAPGrouper, interrupt_main_thread
from _pydevd_bundle.pydevd_daemon_thread import run_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
import tokenize
def _get_code_lines(code):
raise NotImplementedError | null |
177,782 | import sys
import bisect
import types
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_utils, pydevd_source_mapping
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_comm import (InternalGetThreadStack, internal_get_completions,
InternalSetNextStatementThread, internal_reload_code,
InternalGetVariable, InternalGetArray, InternalLoadFullValue,
internal_get_description, internal_get_frame, internal_evaluate_expression, InternalConsoleExec,
internal_get_variable_json, internal_change_variable, internal_change_variable_json,
internal_evaluate_expression_json, internal_set_expression_json, internal_get_exception_details_json,
internal_step_in_thread, internal_smart_step_into)
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, file_system_encoding,
CMD_STEP_INTO_MY_CODE, CMD_STOP_ON_START, CMD_SMART_STEP_INTO)
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, set_protocol, get_protocol,
HTTP_JSON_PROTOCOL, JSON_PROTOCOL, DebugInfoHolder, IS_WINDOWS)
from _pydevd_bundle.pydevd_net_command_factory_json import NetCommandFactoryJson
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
import pydevd_file_utils
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint
from pydevd_tracing import get_exception_traceback_str
import os
import subprocess
import ctypes
from _pydevd_bundle.pydevd_collect_bytecode_info import code_to_bytecode_representation
import itertools
import linecache
from _pydevd_bundle.pydevd_utils import DAPGrouper, interrupt_main_thread
from _pydevd_bundle.pydevd_daemon_thread import run_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
import tokenize
try:
import dis
except ImportError:
else:
def _get_code_lines(code):
if not isinstance(code, types.CodeType):
path = code
with tokenize.open(path) as f:
src = f.read()
code = compile(src, path, 'exec', 0, dont_inherit=True)
return _get_code_lines(code)
def iterate():
# First, get all line starts for this code object. This does not include
# bodies of nested class and function definitions, as they have their
# own objects.
for _, lineno in dis.findlinestarts(code):
yield lineno
# For nested class and function definitions, their respective code objects
# are constants referenced by this object.
for const in code.co_consts:
if isinstance(const, types.CodeType) and const.co_filename == code.co_filename:
for lineno in _get_code_lines(const):
yield lineno
return iterate() | null |
177,783 | import sys
import bisect
import types
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_utils, pydevd_source_mapping
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_comm import (InternalGetThreadStack, internal_get_completions,
InternalSetNextStatementThread, internal_reload_code,
InternalGetVariable, InternalGetArray, InternalLoadFullValue,
internal_get_description, internal_get_frame, internal_evaluate_expression, InternalConsoleExec,
internal_get_variable_json, internal_change_variable, internal_change_variable_json,
internal_evaluate_expression_json, internal_set_expression_json, internal_get_exception_details_json,
internal_step_in_thread, internal_smart_step_into)
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, file_system_encoding,
CMD_STEP_INTO_MY_CODE, CMD_STOP_ON_START, CMD_SMART_STEP_INTO)
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, set_protocol, get_protocol,
HTTP_JSON_PROTOCOL, JSON_PROTOCOL, DebugInfoHolder, IS_WINDOWS)
from _pydevd_bundle.pydevd_net_command_factory_json import NetCommandFactoryJson
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
import pydevd_file_utils
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint
from pydevd_tracing import get_exception_traceback_str
import os
import subprocess
import ctypes
from _pydevd_bundle.pydevd_collect_bytecode_info import code_to_bytecode_representation
import itertools
import linecache
from _pydevd_bundle.pydevd_utils import DAPGrouper, interrupt_main_thread
from _pydevd_bundle.pydevd_daemon_thread import run_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
import tokenize
def _list_ppid_and_pid():
_TH32CS_SNAPPROCESS = 0x00000002
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.c_uint32),
("cntUsage", ctypes.c_uint32),
("th32ProcessID", ctypes.c_uint32),
("th32DefaultHeapID", ctypes.c_size_t),
("th32ModuleID", ctypes.c_uint32),
("cntThreads", ctypes.c_uint32),
("th32ParentProcessID", ctypes.c_uint32),
("pcPriClassBase", ctypes.c_long),
("dwFlags", ctypes.c_uint32),
("szExeFile", ctypes.c_char * 260)]
kernel32 = ctypes.windll.kernel32
snapshot = kernel32.CreateToolhelp32Snapshot(_TH32CS_SNAPPROCESS, 0)
ppid_and_pids = []
try:
process_entry = PROCESSENTRY32()
process_entry.dwSize = ctypes.sizeof(PROCESSENTRY32)
if not kernel32.Process32First(ctypes.c_void_p(snapshot), ctypes.byref(process_entry)):
pydev_log.critical('Process32First failed (getting process from CreateToolhelp32Snapshot).')
else:
while True:
ppid_and_pids.append((process_entry.th32ParentProcessID, process_entry.th32ProcessID))
if not kernel32.Process32Next(ctypes.c_void_p(snapshot), ctypes.byref(process_entry)):
break
finally:
kernel32.CloseHandle(snapshot)
return ppid_and_pids | null |
177,784 | import pydevd_tracing
import greenlet
import gevent
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_custom_frames import add_custom_frame, update_custom_frame, remove_custom_frame
from _pydevd_bundle.pydevd_constants import GEVENT_SHOW_PAUSED_GREENLETS, get_global_debugger, \
thread_get_ident
from _pydev_bundle import pydev_log
from pydevd_file_utils import basename
if GEVENT_SHOW_PAUSED_GREENLETS:
def greenlet_events(event, args):
if event in ('switch', 'throw'):
py_db = get_global_debugger()
origin, target = args
if not origin.dead and origin.gr_frame is not None:
frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.get(origin)
if frame_custom_thread_id is None:
_saved_greenlets_to_custom_frame_thread_id[origin] = add_custom_frame(
origin.gr_frame, _get_paused_name(py_db, origin), thread_get_ident())
else:
update_custom_frame(
frame_custom_thread_id, origin.gr_frame, _get_paused_name(py_db, origin), thread_get_ident())
else:
frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.pop(origin, None)
if frame_custom_thread_id is not None:
remove_custom_frame(frame_custom_thread_id)
# This one will be resumed, so, remove custom frame from it.
frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.pop(target, None)
if frame_custom_thread_id is not None:
remove_custom_frame(frame_custom_thread_id)
# The tracing needs to be reapplied for each greenlet as gevent
# clears the tracing set through sys.settrace for each greenlet.
pydevd_tracing.reapply_settrace()
else:
# i.e.: no logic related to showing paused greenlets is needed.
def greenlet_events(event, args):
pydevd_tracing.reapply_settrace()
GEVENT_SHOW_PAUSED_GREENLETS = is_true_in_env('GEVENT_SHOW_PAUSED_GREENLETS')
def enable_gevent_integration():
# References:
# https://greenlet.readthedocs.io/en/latest/api.html#greenlet.settrace
# https://greenlet.readthedocs.io/en/latest/tracing.html
# Note: gevent.version_info is WRONG (gevent.__version__ must be used).
try:
if tuple(int(x) for x in gevent.__version__.split('.')[:2]) <= (20, 0):
if not GEVENT_SHOW_PAUSED_GREENLETS:
return
if not hasattr(greenlet, 'settrace'):
# In older versions it was optional.
# We still try to use if available though.
pydev_log.debug('greenlet.settrace not available. GEVENT_SHOW_PAUSED_GREENLETS will have no effect.')
return
try:
greenlet.settrace(greenlet_events)
except:
pydev_log.exception('Error with greenlet.settrace.')
except:
pydev_log.exception('Error setting up gevent %s.', gevent.__version__) | null |
177,785 | import pydevd_tracing
import greenlet
import gevent
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_custom_frames import add_custom_frame, update_custom_frame, remove_custom_frame
from _pydevd_bundle.pydevd_constants import GEVENT_SHOW_PAUSED_GREENLETS, get_global_debugger, \
thread_get_ident
from _pydev_bundle import pydev_log
from pydevd_file_utils import basename
def log_gevent_debug_info():
pydev_log.debug('Greenlet version: %s', greenlet.__version__)
pydev_log.debug('Gevent version: %s', gevent.__version__)
pydev_log.debug('Gevent install location: %s', gevent.__file__) | null |
177,786 | from __future__ import nested_scopes
import weakref
import sys
from _pydevd_bundle.pydevd_comm import get_global_debugger
from _pydevd_bundle.pydevd_constants import call_only_once
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_custom_frames import update_custom_frame, remove_custom_frame, add_custom_frame
import stackless
from _pydev_bundle import pydev_log
def register_tasklet_info(tasklet):
r = weakref.ref(tasklet)
info = _weak_tasklet_registered_to_info.get(r)
if info is None:
info = _weak_tasklet_registered_to_info[r] = _TaskletInfo(r, tasklet)
return info
def get_tasklet_info(tasklet):
return register_tasklet_info(tasklet) | null |
177,787 | from __future__ import nested_scopes
import weakref
import sys
from _pydevd_bundle.pydevd_comm import get_global_debugger
from _pydevd_bundle.pydevd_constants import call_only_once
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_custom_frames import update_custom_frame, remove_custom_frame, add_custom_frame
import stackless
from _pydev_bundle import pydev_log
_application_set_schedule_callback = None
def _schedule_callback(prev, next):
'''
Called when a context is stopped or a new context is made runnable.
'''
try:
if not prev and not next:
return
current_frame = sys._getframe()
if next:
register_tasklet_info(next)
# Ok, making next runnable: set the tracing facility in it.
debugger = get_global_debugger()
if debugger is not None:
next.trace_function = debugger.get_thread_local_trace_func()
frame = next.frame
if frame is current_frame:
frame = frame.f_back
if hasattr(frame, 'f_trace'): # Note: can be None (but hasattr should cover for that too).
frame.f_trace = debugger.get_thread_local_trace_func()
debugger = None
if prev:
register_tasklet_info(prev)
try:
for tasklet_ref, tasklet_info in list(_weak_tasklet_registered_to_info.items()): # Make sure it's a copy!
tasklet = tasklet_ref()
if tasklet is None or not tasklet.alive:
# Garbage-collected already!
try:
del _weak_tasklet_registered_to_info[tasklet_ref]
except KeyError:
pass
if tasklet_info.frame_id is not None:
remove_custom_frame(tasklet_info.frame_id)
else:
is_running = stackless.get_thread_info(tasklet.thread_id)[1] is tasklet
if tasklet is prev or (tasklet is not next and not is_running):
# the tasklet won't run after this scheduler action:
# - the tasklet is the previous tasklet
# - it is not the next tasklet and it is not an already running tasklet
frame = tasklet.frame
if frame is current_frame:
frame = frame.f_back
if frame is not None:
# print >>sys.stderr, "SchedCB: %r, %d, '%s', '%s'" % (tasklet, frame.f_lineno, _filename, base)
debugger = get_global_debugger()
if debugger is not None and debugger.get_file_type(frame) is None:
tasklet_info.update_name()
if tasklet_info.frame_id is None:
tasklet_info.frame_id = add_custom_frame(frame, tasklet_info.tasklet_name, tasklet.thread_id)
else:
update_custom_frame(tasklet_info.frame_id, frame, tasklet.thread_id, name=tasklet_info.tasklet_name)
debugger = None
elif tasklet is next or is_running:
if tasklet_info.frame_id is not None:
# Remove info about stackless suspended when it starts to run.
remove_custom_frame(tasklet_info.frame_id)
tasklet_info.frame_id = None
finally:
tasklet = None
tasklet_info = None
frame = None
except:
pydev_log.exception()
if _application_set_schedule_callback is not None:
return _application_set_schedule_callback(prev, next)
if not hasattr(stackless.tasklet, "trace_function"):
# Older versions of Stackless, released before 2014
# This code does not work reliable! It is affected by several
# stackless bugs: Stackless issues #44, #42, #40
def _schedule_callback(prev, next):
'''
Called when a context is stopped or a new context is made runnable.
'''
try:
if not prev and not next:
return
if next:
register_tasklet_info(next)
# Ok, making next runnable: set the tracing facility in it.
debugger = get_global_debugger()
if debugger is not None and next.frame:
if hasattr(next.frame, 'f_trace'):
next.frame.f_trace = debugger.get_thread_local_trace_func()
debugger = None
if prev:
register_tasklet_info(prev)
try:
for tasklet_ref, tasklet_info in list(_weak_tasklet_registered_to_info.items()): # Make sure it's a copy!
tasklet = tasklet_ref()
if tasklet is None or not tasklet.alive:
# Garbage-collected already!
try:
del _weak_tasklet_registered_to_info[tasklet_ref]
except KeyError:
pass
if tasklet_info.frame_id is not None:
remove_custom_frame(tasklet_info.frame_id)
else:
if tasklet.paused or tasklet.blocked or tasklet.scheduled:
if tasklet.frame and tasklet.frame.f_back:
f_back = tasklet.frame.f_back
debugger = get_global_debugger()
if debugger is not None and debugger.get_file_type(f_back) is None:
if tasklet_info.frame_id is None:
tasklet_info.frame_id = add_custom_frame(f_back, tasklet_info.tasklet_name, tasklet.thread_id)
else:
update_custom_frame(tasklet_info.frame_id, f_back, tasklet.thread_id)
debugger = None
elif tasklet.is_current:
if tasklet_info.frame_id is not None:
# Remove info about stackless suspended when it starts to run.
remove_custom_frame(tasklet_info.frame_id)
tasklet_info.frame_id = None
finally:
tasklet = None
tasklet_info = None
f_back = None
except:
pydev_log.exception()
if _application_set_schedule_callback is not None:
return _application_set_schedule_callback(prev, next)
_original_setup = stackless.tasklet.setup
#=======================================================================================================================
# setup
#=======================================================================================================================
def setup(self, *args, **kwargs):
'''
Called to run a new tasklet: rebind the creation so that we can trace it.
'''
f = self.tempval
def new_f(old_f, args, kwargs):
debugger = get_global_debugger()
if debugger is not None:
debugger.enable_tracing()
debugger = None
# Remove our own traces :)
self.tempval = old_f
register_tasklet_info(self)
# Hover old_f to see the stackless being created and *args and **kwargs to see its parameters.
return old_f(*args, **kwargs)
# This is the way to tell stackless that the function it should execute is our function, not the original one. Note:
# setting tempval is the same as calling bind(new_f), but it seems that there's no other way to get the currently
# bound function, so, keeping on using tempval instead of calling bind (which is actually the same thing in a better
# API).
self.tempval = new_f
return _original_setup(self, f, args, kwargs)
#=======================================================================================================================
# __call__
#=======================================================================================================================
def __call__(self, *args, **kwargs):
'''
Called to run a new tasklet: rebind the creation so that we can trace it.
'''
return setup(self, *args, **kwargs)
_original_run = stackless.run
#=======================================================================================================================
# run
#=======================================================================================================================
def run(*args, **kwargs):
debugger = get_global_debugger()
if debugger is not None:
debugger.enable_tracing()
debugger = None
return _original_run(*args, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `patch_stackless` function. Write a Python function `def patch_stackless()` to solve the following problem:
This function should be called to patch the stackless module so that new tasklets are properly tracked in the debugger.
Here is the function:
def patch_stackless():
'''
This function should be called to patch the stackless module so that new tasklets are properly tracked in the
debugger.
'''
global _application_set_schedule_callback
_application_set_schedule_callback = stackless.set_schedule_callback(_schedule_callback)
def set_schedule_callback(callable):
global _application_set_schedule_callback
old = _application_set_schedule_callback
_application_set_schedule_callback = callable
return old
def get_schedule_callback():
global _application_set_schedule_callback
return _application_set_schedule_callback
set_schedule_callback.__doc__ = stackless.set_schedule_callback.__doc__
if hasattr(stackless, "get_schedule_callback"):
get_schedule_callback.__doc__ = stackless.get_schedule_callback.__doc__
stackless.set_schedule_callback = set_schedule_callback
stackless.get_schedule_callback = get_schedule_callback
if not hasattr(stackless.tasklet, "trace_function"):
# Older versions of Stackless, released before 2014
__call__.__doc__ = stackless.tasklet.__call__.__doc__
stackless.tasklet.__call__ = __call__
setup.__doc__ = stackless.tasklet.setup.__doc__
stackless.tasklet.setup = setup
run.__doc__ = stackless.run.__doc__
stackless.run = run | This function should be called to patch the stackless module so that new tasklets are properly tracked in the debugger. |
177,788 | import linecache
import re
def default_should_trace_hook(frame, absolute_filename):
'''
Return True if this frame should be traced, False if tracing should be blocked.
'''
# First, check whether this code object has a cached value
ignored_lines = _filename_to_ignored_lines.get(absolute_filename)
if ignored_lines is None:
# Now, look up that line of code and check for a @DontTrace
# preceding or on the same line as the method.
# E.g.:
# #@DontTrace
# def test():
# pass
# ... or ...
# def test(): #@DontTrace
# pass
ignored_lines = {}
lines = linecache.getlines(absolute_filename)
for i_line, line in enumerate(lines):
j = line.find('#')
if j >= 0:
comment = line[j:]
if DONT_TRACE_TAG in comment:
ignored_lines[i_line] = 1
# Note: when it's found in the comment, mark it up and down for the decorator lines found.
k = i_line - 1
while k >= 0:
if RE_DECORATOR.match(lines[k]):
ignored_lines[k] = 1
k -= 1
else:
break
k = i_line + 1
while k <= len(lines):
if RE_DECORATOR.match(lines[k]):
ignored_lines[k] = 1
k += 1
else:
break
_filename_to_ignored_lines[absolute_filename] = ignored_lines
func_line = frame.f_code.co_firstlineno - 1 # co_firstlineno is 1-based, so -1 is needed
return not (
func_line - 1 in ignored_lines or # -1 to get line before method
func_line in ignored_lines) # method line
should_trace_hook = None
The provided code snippet includes necessary dependencies for implementing the `trace_filter` function. Write a Python function `def trace_filter(mode)` to solve the following problem:
Set the trace filter mode. mode: Whether to enable the trace hook. True: Trace filtering on (skipping methods tagged @DontTrace) False: Trace filtering off (trace methods tagged @DontTrace) None/default: Toggle trace filtering.
Here is the function:
def trace_filter(mode):
'''
Set the trace filter mode.
mode: Whether to enable the trace hook.
True: Trace filtering on (skipping methods tagged @DontTrace)
False: Trace filtering off (trace methods tagged @DontTrace)
None/default: Toggle trace filtering.
'''
global should_trace_hook
if mode is None:
mode = should_trace_hook is None
if mode:
should_trace_hook = default_should_trace_hook
else:
should_trace_hook = None
return mode | Set the trace filter mode. mode: Whether to enable the trace hook. True: Trace filtering on (skipping methods tagged @DontTrace) False: Trace filtering off (trace methods tagged @DontTrace) None/default: Toggle trace filtering. |
177,789 | from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
ID_TO_MEANING = {
'101': 'CMD_RUN',
'102': 'CMD_LIST_THREADS',
'103': 'CMD_THREAD_CREATE',
'104': 'CMD_THREAD_KILL',
'105': 'CMD_THREAD_SUSPEND',
'106': 'CMD_THREAD_RUN',
'107': 'CMD_STEP_INTO',
'108': 'CMD_STEP_OVER',
'109': 'CMD_STEP_RETURN',
'110': 'CMD_GET_VARIABLE',
'111': 'CMD_SET_BREAK',
'112': 'CMD_REMOVE_BREAK',
'113': 'CMD_EVALUATE_EXPRESSION',
'114': 'CMD_GET_FRAME',
'115': 'CMD_EXEC_EXPRESSION',
'116': 'CMD_WRITE_TO_CONSOLE',
'117': 'CMD_CHANGE_VARIABLE',
'118': 'CMD_RUN_TO_LINE',
'119': 'CMD_RELOAD_CODE',
'120': 'CMD_GET_COMPLETIONS',
'121': 'CMD_CONSOLE_EXEC',
'122': 'CMD_ADD_EXCEPTION_BREAK',
'123': 'CMD_REMOVE_EXCEPTION_BREAK',
'124': 'CMD_LOAD_SOURCE',
'125': 'CMD_ADD_DJANGO_EXCEPTION_BREAK',
'126': 'CMD_REMOVE_DJANGO_EXCEPTION_BREAK',
'127': 'CMD_SET_NEXT_STATEMENT',
'128': 'CMD_SMART_STEP_INTO',
'129': 'CMD_EXIT',
'130': 'CMD_SIGNATURE_CALL_TRACE',
'131': 'CMD_SET_PY_EXCEPTION',
'132': 'CMD_GET_FILE_CONTENTS',
'133': 'CMD_SET_PROPERTY_TRACE',
'134': 'CMD_EVALUATE_CONSOLE_EXPRESSION',
'135': 'CMD_RUN_CUSTOM_OPERATION',
'136': 'CMD_GET_BREAKPOINT_EXCEPTION',
'137': 'CMD_STEP_CAUGHT_EXCEPTION',
'138': 'CMD_SEND_CURR_EXCEPTION_TRACE',
'139': 'CMD_SEND_CURR_EXCEPTION_TRACE_PROCEEDED',
'140': 'CMD_IGNORE_THROWN_EXCEPTION_AT',
'141': 'CMD_ENABLE_DONT_TRACE',
'142': 'CMD_SHOW_CONSOLE',
'143': 'CMD_GET_ARRAY',
'144': 'CMD_STEP_INTO_MY_CODE',
'145': 'CMD_GET_CONCURRENCY_EVENT',
'146': 'CMD_SHOW_RETURN_VALUES',
'147': 'CMD_INPUT_REQUESTED',
'148': 'CMD_GET_DESCRIPTION',
'149': 'CMD_PROCESS_CREATED', # Note: this is actually a notification of a sub-process created.
'150': 'CMD_SHOW_CYTHON_WARNING',
'151': 'CMD_LOAD_FULL_VALUE',
'152': 'CMD_GET_THREAD_STACK',
'153': 'CMD_THREAD_DUMP_TO_STDERR',
'154': 'CMD_STOP_ON_START',
'155': 'CMD_GET_EXCEPTION_DETAILS',
'156': 'CMD_PYDEVD_JSON_CONFIG',
'157': 'CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION',
'158': 'CMD_THREAD_RESUME_SINGLE_NOTIFICATION',
'159': 'CMD_STEP_OVER_MY_CODE',
'160': 'CMD_STEP_RETURN_MY_CODE',
'161': 'CMD_SET_PY_EXCEPTION_JSON',
'162': 'CMD_SET_PATH_MAPPING_JSON',
'163': 'CMD_GET_SMART_STEP_INTO_VARIANTS',
'200': 'CMD_REDIRECT_OUTPUT',
'201': 'CMD_GET_NEXT_STATEMENT_TARGETS',
'202': 'CMD_SET_PROJECT_ROOTS',
'203': 'CMD_MODULE_EVENT',
'204': 'CMD_PROCESS_EVENT', # DAP process event.
'205': 'CMD_AUTHENTICATE',
'206': 'CMD_STEP_INTO_COROUTINE',
'207': 'CMD_LOAD_SOURCE_FROM_FRAME_ID',
'501': 'CMD_VERSION',
'502': 'CMD_RETURN',
'503': 'CMD_SET_PROTOCOL',
'901': 'CMD_ERROR',
}
def constant_to_str(constant):
s = ID_TO_MEANING.get(str(constant))
if not s:
s = '<Unknown: %s>' % (constant,)
return s | null |
177,790 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def version_str(v):
return '.'.join((str(x) for x in v[:3])) + ''.join((str(x) for x in v[3:])) | null |
177,791 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
ENV_TRUE_LOWER_VALUES = ('yes', 'true', '1')
from _pydev_bundle._pydev_saved_modules import thread, threading
def is_true_in_env(env_key):
if isinstance(env_key, tuple):
# If a tuple, return True if any of those ends up being true.
for v in env_key:
if is_true_in_env(v):
return True
return False
else:
return os.getenv(env_key, '').lower() in ENV_TRUE_LOWER_VALUES | null |
177,792 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def as_float_in_env(env_key, default):
value = os.getenv(env_key)
if value is None:
return default
try:
return float(value)
except Exception:
raise RuntimeError(
'Error: expected the env variable: %s to be set to a float value. Found: %s' % (
env_key, value)) | null |
177,793 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def as_int_in_env(env_key, default):
value = os.getenv(env_key)
if value is None:
return default
try:
return int(value)
except Exception:
raise RuntimeError(
'Error: expected the env variable: %s to be set to a int value. Found: %s' % (
env_key, value)) | null |
177,794 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
The provided code snippet includes necessary dependencies for implementing the `protect_libraries_from_patching` function. Write a Python function `def protect_libraries_from_patching()` to solve the following problem:
In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patching by external libraries (e.g. gevent).
Here is the function:
def protect_libraries_from_patching():
"""
In this function we delete some modules from `sys.modules` dictionary and import them again inside
`_pydev_saved_modules` in order to save their original copies there. After that we can use these
saved modules within the debugger to protect them from patching by external libraries (e.g. gevent).
"""
patched = ['threading', 'thread', '_thread', 'time', 'socket', 'queue', 'select',
'xmlrpclib', 'SimpleXMLRPCServer', 'BaseHTTPServer', 'SocketServer',
'xmlrpc.client', 'xmlrpc.server', 'http.server', 'socketserver']
for name in patched:
try:
__import__(name)
except:
pass
patched_modules = dict([(k, v) for k, v in sys.modules.items()
if k in patched])
for name in patched_modules:
del sys.modules[name]
# import for side effects
import _pydev_bundle._pydev_saved_modules
for name in patched_modules:
sys.modules[name] = patched_modules[name] | In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patching by external libraries (e.g. gevent). |
177,795 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def as_str(s):
assert isinstance(s, str)
return s | null |
177,796 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def filter_all_warnings():
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
yield
def silence_warnings_decorator(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
with filter_all_warnings():
return func(*args, **kwargs)
return new_func | null |
177,797 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
def _temp_trace(frame, event, arg):
return None | null |
177,798 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
The provided code snippet includes necessary dependencies for implementing the `_check_ftrace_set_none` function. Write a Python function `def _check_ftrace_set_none()` to solve the following problem:
Will throw an error when executing a line event
Here is the function:
def _check_ftrace_set_none():
'''
Will throw an error when executing a line event
'''
sys._getframe().f_trace = None
_line_event = 1
_line_event = 2 | Will throw an error when executing a line event |
177,799 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
_thread_id_lock = ForkSafeLock()
def clear_cached_thread_id(thread):
with _thread_id_lock:
try:
if thread.__pydevd_id__ != 'console_main':
# The console_main is a special thread id used in the console and its id should never be reset
# (otherwise we may no longer be able to get its variables -- see: https://www.brainwy.com/tracker/PyDev/776).
del thread.__pydevd_id__
except AttributeError:
pass | null |
177,800 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
_thread_id_lock = ForkSafeLock()
def set_thread_id(thread, thread_id):
with _thread_id_lock:
thread.__pydevd_id__ = thread_id | null |
177,801 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
The provided code snippet includes necessary dependencies for implementing the `call_only_once` function. Write a Python function `def call_only_once(func)` to solve the following problem:
To be used as a decorator @call_only_once def func(): print 'Calling func only this time' Actually, in PyDev it must be called as: func = call_only_once(func) to support older versions of Python.
Here is the function:
def call_only_once(func):
'''
To be used as a decorator
@call_only_once
def func():
print 'Calling func only this time'
Actually, in PyDev it must be called as:
func = call_only_once(func) to support older versions of Python.
'''
def new_func(*args, **kwargs):
if not new_func._called:
new_func._called = True
return func(*args, **kwargs)
new_func._called = False
return new_func | To be used as a decorator @call_only_once def func(): print 'Calling func only this time' Actually, in PyDev it must be called as: func = call_only_once(func) to support older versions of Python. |
177,802 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
QUOTED_LINE_PROTOCOL = 'quoted-line'
HTTP_PROTOCOL = 'http'
JSON_PROTOCOL = 'json'
HTTP_JSON_PROTOCOL = 'http_json'
class _GlobalSettings:
protocol = QUOTED_LINE_PROTOCOL
def set_protocol(protocol):
expected = (HTTP_PROTOCOL, QUOTED_LINE_PROTOCOL, JSON_PROTOCOL, HTTP_JSON_PROTOCOL)
assert protocol in expected, 'Protocol (%s) should be one of: %s' % (
protocol, expected)
_GlobalSettings.protocol = protocol | null |
177,803 | from __future__ import nested_scopes
import platform
import weakref
import struct
import warnings
import functools
from contextlib import contextmanager
import sys
import codecs as _codecs
import os
from _pydevd_bundle import pydevd_vm_type
from _pydev_bundle._pydev_saved_modules import thread, threading
JSON_PROTOCOL = 'json'
HTTP_JSON_PROTOCOL = 'http_json'
class _GlobalSettings:
protocol = QUOTED_LINE_PROTOCOL
def is_json_protocol():
return _GlobalSettings.protocol in (JSON_PROTOCOL, HTTP_JSON_PROTOCOL) | null |
177,804 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
class VariableError(RuntimeError):
pass
def iter_frames(frame):
while frame is not None:
yield frame
frame = frame.f_back
frame = None
try:
get_frame = sys._getframe
if IS_IRONPYTHON:
def get_frame():
try:
return sys._getframe()
except ValueError:
pass
except AttributeError:
def get_frame():
raise AssertionError('sys._getframe not available (possible causes: enable -X:Frames on IronPython?)')
def get_current_thread_id(thread):
'''
Note: the difference from get_current_thread_id to get_thread_id is that
for the current thread we can get the thread id while the thread.ident
is still not set in the Thread instance.
'''
try:
# Fast path without getting lock.
tid = thread.__pydevd_id__
if tid is None:
# Fix for https://www.brainwy.com/tracker/PyDev/645
# if __pydevd_id__ is None, recalculate it... also, use an heuristic
# that gives us always the same id for the thread (using thread.ident or id(thread)).
raise AttributeError()
except AttributeError:
tid = _get_or_compute_thread_id_with_lock(thread, is_current_thread=True)
return tid
def dump_frames(thread_id):
sys.stdout.write('dumping frames\n')
if thread_id != get_current_thread_id(threading.current_thread()):
raise VariableError("find_frame: must execute on same thread")
frame = get_frame()
for frame in iter_frames(frame):
sys.stdout.write('%s\n' % pickle.dumps(frame)) | null |
177,805 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
def getVariable(dbg, thread_id, frame_id, scope, locator):
"""
returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:locator: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj\tattr1\tattr2)
:note: when BY_ID is used, the frame_id is considered the id of the object to find and
not the frame (as we don't care about the frame in this case).
"""
if scope == 'BY_ID':
if thread_id != get_current_thread_id(threading.current_thread()):
raise VariableError("getVariable: must execute on same thread")
try:
import gc
objects = gc.get_objects()
except:
pass # Not all python variants have it.
else:
frame_id = int(frame_id)
for var in objects:
if id(var) == frame_id:
if locator is not None:
locator_parts = locator.split('\t')
for k in locator_parts:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
return var
# If it didn't return previously, we coudn't find it by id (i.e.: already garbage collected).
sys.stderr.write('Unable to find object with id: %s\n' % (frame_id,))
return None
frame = dbg.find_frame(thread_id, frame_id)
if frame is None:
return {}
if locator is not None:
locator_parts = locator.split('\t')
else:
locator_parts = []
for attr in locator_parts:
attr.replace("@_@TAB_CHAR@_@", '\t')
if scope == 'EXPRESSION':
for count in range(len(locator_parts)):
if count == 0:
# An Expression can be in any scope (globals/locals), therefore it needs to evaluated as an expression
var = evaluate_expression(dbg, frame, locator_parts[count], False)
else:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, locator_parts[count])
else:
if scope == "GLOBAL":
var = frame.f_globals
del locator_parts[0] # globals are special, and they get a single dummy unused attribute
else:
# in a frame access both locals and globals as Python does
var = {}
var.update(frame.f_globals)
var.update(frame.f_locals)
for k in locator_parts:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
return var
get_type = _TYPE_RESOLVE_HANDLER.get_type
The provided code snippet includes necessary dependencies for implementing the `resolve_compound_variable_fields` function. Write a Python function `def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs)` to solve the following problem:
Resolve compound variable in debugger scopes by its name and attributes :param thread_id: id of the variable's thread :param frame_id: id of the variable's frame :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME :param attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields
Here is the function:
def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs):
"""
Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
:param attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj\tattr1\tattr2)
:return: a dictionary of variables's fields
"""
var = getVariable(dbg, thread_id, frame_id, scope, attrs)
try:
_type, type_name, resolver = get_type(var)
return type_name, resolver.get_dictionary(var)
except:
pydev_log.exception('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s.',
thread_id, frame_id, scope, attrs) | Resolve compound variable in debugger scopes by its name and attributes :param thread_id: id of the variable's thread :param frame_id: id of the variable's frame :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME :param attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields |
177,806 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
get_type = _TYPE_RESOLVE_HANDLER.get_type
The provided code snippet includes necessary dependencies for implementing the `resolve_var_object` function. Write a Python function `def resolve_var_object(var, attrs)` to solve the following problem:
Resolve variable's attribute :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a value of resolved variable's attribute
Here is the function:
def resolve_var_object(var, attrs):
"""
Resolve variable's attribute
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)
:return: a value of resolved variable's attribute
"""
if attrs is not None:
attr_list = attrs.split('\t')
else:
attr_list = []
for k in attr_list:
type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
return var | Resolve variable's attribute :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a value of resolved variable's attribute |
177,807 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
get_type = _TYPE_RESOLVE_HANDLER.get_type
The provided code snippet includes necessary dependencies for implementing the `resolve_compound_var_object_fields` function. Write a Python function `def resolve_compound_var_object_fields(var, attrs)` to solve the following problem:
Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields
Here is the function:
def resolve_compound_var_object_fields(var, attrs):
"""
Resolve compound variable by its object and attributes
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)
:return: a dictionary of variables's fields
"""
attr_list = attrs.split('\t')
for k in attr_list:
type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
try:
type, _type_name, resolver = get_type(var)
return resolver.get_dictionary(var)
except:
pydev_log.exception() | Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields |
177,808 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
def getVariable(dbg, thread_id, frame_id, scope, locator):
"""
returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:locator: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj\tattr1\tattr2)
:note: when BY_ID is used, the frame_id is considered the id of the object to find and
not the frame (as we don't care about the frame in this case).
"""
if scope == 'BY_ID':
if thread_id != get_current_thread_id(threading.current_thread()):
raise VariableError("getVariable: must execute on same thread")
try:
import gc
objects = gc.get_objects()
except:
pass # Not all python variants have it.
else:
frame_id = int(frame_id)
for var in objects:
if id(var) == frame_id:
if locator is not None:
locator_parts = locator.split('\t')
for k in locator_parts:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
return var
# If it didn't return previously, we coudn't find it by id (i.e.: already garbage collected).
sys.stderr.write('Unable to find object with id: %s\n' % (frame_id,))
return None
frame = dbg.find_frame(thread_id, frame_id)
if frame is None:
return {}
if locator is not None:
locator_parts = locator.split('\t')
else:
locator_parts = []
for attr in locator_parts:
attr.replace("@_@TAB_CHAR@_@", '\t')
if scope == 'EXPRESSION':
for count in range(len(locator_parts)):
if count == 0:
# An Expression can be in any scope (globals/locals), therefore it needs to evaluated as an expression
var = evaluate_expression(dbg, frame, locator_parts[count], False)
else:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, locator_parts[count])
else:
if scope == "GLOBAL":
var = frame.f_globals
del locator_parts[0] # globals are special, and they get a single dummy unused attribute
else:
# in a frame access both locals and globals as Python does
var = {}
var.update(frame.f_globals)
var.update(frame.f_locals)
for k in locator_parts:
_type, _type_name, resolver = get_type(var)
var = resolver.resolve(var, k)
return var
The provided code snippet includes necessary dependencies for implementing the `custom_operation` function. Write a Python function `def custom_operation(dbg, thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name)` to solve the following problem:
We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var. code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed. operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)
Here is the function:
def custom_operation(dbg, thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
"""
We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.
code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.
operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)
"""
expressionValue = getVariable(dbg, thread_id, frame_id, scope, attrs)
try:
namespace = {'__name__': '<custom_operation>'}
if style == "EXECFILE":
namespace['__file__'] = code_or_file
execfile(code_or_file, namespace, namespace)
else: # style == EXEC
namespace['__file__'] = '<customOperationCode>'
Exec(code_or_file, namespace, namespace)
return str(namespace[operation_fn_name](expressionValue))
except:
pydev_log.exception() | We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var. code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed. operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint) |
177,809 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
def _run_with_unblock_threads(original_func, py_db, curr_thread, frame, expression, is_exec):
on_timeout_unblock_threads = None
timeout_tracker = py_db.timeout_tracker # : :type timeout_tracker: TimeoutTracker
if py_db.multi_threads_single_notification:
unblock_threads_timeout = pydevd_constants.PYDEVD_UNBLOCK_THREADS_TIMEOUT
else:
unblock_threads_timeout = -1 # Don't use this if threads are managed individually.
if unblock_threads_timeout >= 0:
pydev_log.info('Doing evaluate with unblock threads timeout: %s.', unblock_threads_timeout)
tid = get_current_thread_id(curr_thread)
def on_timeout_unblock_threads():
on_timeout_unblock_threads.called = True
pydev_log.info('Resuming threads after evaluate timeout.')
resume_threads('*', except_thread=curr_thread)
py_db.threads_suspended_single_notification.on_thread_resume(tid, curr_thread)
on_timeout_unblock_threads.called = False
try:
if on_timeout_unblock_threads is None:
return _run_with_interrupt_thread(original_func, py_db, curr_thread, frame, expression, is_exec)
else:
with timeout_tracker.call_on_timeout(unblock_threads_timeout, on_timeout_unblock_threads):
return _run_with_interrupt_thread(original_func, py_db, curr_thread, frame, expression, is_exec)
finally:
if on_timeout_unblock_threads is not None and on_timeout_unblock_threads.called:
mark_thread_suspended(curr_thread, CMD_SET_BREAK)
py_db.threads_suspended_single_notification.increment_suspend_time()
suspend_all_threads(py_db, except_thread=curr_thread)
py_db.threads_suspended_single_notification.on_thread_suspend(tid, curr_thread, CMD_SET_BREAK)
The provided code snippet includes necessary dependencies for implementing the `_evaluate_with_timeouts` function. Write a Python function `def _evaluate_with_timeouts(original_func)` to solve the following problem:
Provides a decorator that wraps the original evaluate to deal with slow evaluates. If some evaluation is too slow, we may show a message, resume threads or interrupt them as needed (based on the related configurations).
Here is the function:
def _evaluate_with_timeouts(original_func):
'''
Provides a decorator that wraps the original evaluate to deal with slow evaluates.
If some evaluation is too slow, we may show a message, resume threads or interrupt them
as needed (based on the related configurations).
'''
@functools.wraps(original_func)
def new_func(py_db, frame, expression, is_exec):
if py_db is None:
# Only for testing...
pydev_log.critical('_evaluate_with_timeouts called without py_db!')
return original_func(py_db, frame, expression, is_exec)
warn_evaluation_timeout = pydevd_constants.PYDEVD_WARN_EVALUATION_TIMEOUT
curr_thread = threading.current_thread()
def on_warn_evaluation_timeout():
py_db.writer.add_command(py_db.cmd_factory.make_evaluation_timeout_msg(
py_db, expression, curr_thread))
timeout_tracker = py_db.timeout_tracker # : :type timeout_tracker: TimeoutTracker
with timeout_tracker.call_on_timeout(warn_evaluation_timeout, on_warn_evaluation_timeout):
return _run_with_unblock_threads(original_func, py_db, curr_thread, frame, expression, is_exec)
return new_func | Provides a decorator that wraps the original evaluate to deal with slow evaluates. If some evaluation is too slow, we may show a message, resume threads or interrupt them as needed (based on the related configurations). |
177,810 | import pickle
from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \
iter_chars, silence_warnings_decorator, get_global_debugger
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml
from _pydev_bundle import pydev_log
import functools
from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads
from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants
from _pydev_bundle.pydev_imports import Exec, execfile
from _pydevd_bundle.pydevd_utils import to_string
import inspect
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
from functools import lru_cache
class VariableError(RuntimeError):
pass
def array_to_xml(array, roffset, coffset, rows, cols, format):
xml = ""
rows = min(rows, MAXIMUM_ARRAY_SIZE)
cols = min(cols, MAXIMUM_ARRAY_SIZE)
# there is no obvious rule for slicing (at least 5 choices)
if len(array) == 1 and (rows > 1 or cols > 1):
array = array[0]
if array.size > len(array):
array = array[roffset:, coffset:]
rows = min(rows, len(array))
cols = min(cols, len(array[0]))
if len(array) == 1:
array = array[0]
elif array.size == len(array):
if roffset == 0 and rows == 1:
array = array[coffset:]
cols = min(cols, len(array))
elif coffset == 0 and cols == 1:
array = array[roffset:]
rows = min(rows, len(array))
xml += "<arraydata rows=\"%s\" cols=\"%s\"/>" % (rows, cols)
for row in range(rows):
xml += "<row index=\"%s\"/>" % to_string(row)
for col in range(cols):
value = array
if rows == 1 or cols == 1:
if rows == 1 and cols == 1:
value = array[0]
else:
if rows == 1:
dim = col
else:
dim = row
value = array[dim]
if "ndarray" in str(type(value)):
value = value[0]
else:
value = array[row][col]
value = format % value
xml += var_to_xml(value, '')
return xml
def array_to_meta_xml(array, name, format):
type = array.dtype.kind
slice = name
l = len(array.shape)
# initial load, compute slice
if format == '%':
if l > 2:
slice += '[0]' * (l - 2)
for r in range(l - 2):
array = array[0]
if type == 'f':
format = '.5f'
elif type == 'i' or type == 'u':
format = 'd'
else:
format = 's'
else:
format = format.replace('%', '')
l = len(array.shape)
reslice = ""
if l > 2:
raise Exception("%s has more than 2 dimensions." % slice)
elif l == 1:
# special case with 1D arrays arr[i, :] - row, but arr[:, i] - column with equal shape and ndim
# http://stackoverflow.com/questions/16837946/numpy-a-2-rows-1-column-file-loadtxt-returns-1row-2-columns
# explanation: http://stackoverflow.com/questions/15165170/how-do-i-maintain-row-column-orientation-of-vectors-in-numpy?rq=1
# we use kind of a hack - get information about memory from C_CONTIGUOUS
is_row = array.flags['C_CONTIGUOUS']
if is_row:
rows = 1
cols = min(len(array), MAX_SLICE_SIZE)
if cols < len(array):
reslice = '[0:%s]' % (cols)
array = array[0:cols]
else:
cols = 1
rows = min(len(array), MAX_SLICE_SIZE)
if rows < len(array):
reslice = '[0:%s]' % (rows)
array = array[0:rows]
elif l == 2:
rows = min(array.shape[-2], MAX_SLICE_SIZE)
cols = min(array.shape[-1], MAX_SLICE_SIZE)
if cols < array.shape[-1] or rows < array.shape[-2]:
reslice = '[0:%s, 0:%s]' % (rows, cols)
array = array[0:rows, 0:cols]
# avoid slice duplication
if not slice.endswith(reslice):
slice += reslice
bounds = (0, 0)
if type in "biufc":
bounds = (array.min(), array.max())
xml = '<array slice=\"%s\" rows=\"%s\" cols=\"%s\" format=\"%s\" type=\"%s\" max=\"%s\" min=\"%s\"/>' % \
(slice, rows, cols, format, type, bounds[1], bounds[0])
return array, xml, rows, cols, format
def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format):
"""
:type df: pandas.core.frame.DataFrame
:type name: str
:type coffset: int
:type roffset: int
:type rows: int
:type cols: int
:type format: str
"""
num_rows = min(df.shape[0], MAX_SLICE_SIZE)
num_cols = min(df.shape[1], MAX_SLICE_SIZE)
if (num_rows, num_cols) != df.shape:
df = df.iloc[0:num_rows, 0: num_cols]
slice = '.iloc[0:%s, 0:%s]' % (num_rows, num_cols)
else:
slice = ''
slice = name + slice
xml = '<array slice=\"%s\" rows=\"%s\" cols=\"%s\" format=\"\" type=\"\" max=\"0\" min=\"0\"/>\n' % \
(slice, num_rows, num_cols)
if (rows, cols) == (-1, -1):
rows, cols = num_rows, num_cols
rows = min(rows, MAXIMUM_ARRAY_SIZE)
cols = min(min(cols, MAXIMUM_ARRAY_SIZE), num_cols)
# need to precompute column bounds here before slicing!
col_bounds = [None] * cols
for col in range(cols):
dtype = df.dtypes.iloc[coffset + col].kind
if dtype in "biufc":
cvalues = df.iloc[:, coffset + col]
bounds = (cvalues.min(), cvalues.max())
else:
bounds = (0, 0)
col_bounds[col] = bounds
df = df.iloc[roffset: roffset + rows, coffset: coffset + cols]
rows, cols = df.shape
xml += "<headerdata rows=\"%s\" cols=\"%s\">\n" % (rows, cols)
format = format.replace('%', '')
col_formats = []
get_label = lambda label: str(label) if not isinstance(label, tuple) else '/'.join(map(str, label))
for col in range(cols):
dtype = df.dtypes.iloc[col].kind
if dtype == 'f' and format:
fmt = format
elif dtype == 'f':
fmt = '.5f'
elif dtype == 'i' or dtype == 'u':
fmt = 'd'
else:
fmt = 's'
col_formats.append('%' + fmt)
bounds = col_bounds[col]
xml += '<colheader index=\"%s\" label=\"%s\" type=\"%s\" format=\"%s\" max=\"%s\" min=\"%s\" />\n' % \
(str(col), get_label(df.axes[1].values[col]), dtype, fmt, bounds[1], bounds[0])
for row, label in enumerate(iter(df.axes[0])):
xml += "<rowheader index=\"%s\" label = \"%s\"/>\n" % \
(str(row), get_label(label))
xml += "</headerdata>\n"
xml += "<arraydata rows=\"%s\" cols=\"%s\"/>\n" % (rows, cols)
for row in range(rows):
xml += "<row index=\"%s\"/>\n" % str(row)
for col in range(cols):
value = df.iat[row, col]
value = col_formats[col] % value
xml += var_to_xml(value, '')
return xml
get_type = _TYPE_RESOLVE_HANDLER.get_type
def table_like_struct_to_xml(array, name, roffset, coffset, rows, cols, format):
_, type_name, _ = get_type(array)
if type_name == 'ndarray':
array, metaxml, r, c, f = array_to_meta_xml(array, name, format)
xml = metaxml
format = '%' + f
if rows == -1 and cols == -1:
rows = r
cols = c
xml += array_to_xml(array, roffset, coffset, rows, cols, format)
elif type_name == 'DataFrame':
xml = dataframe_to_xml(array, name, roffset, coffset, rows, cols, format)
else:
raise VariableError("Do not know how to convert type %s to table" % (type_name))
return "<xml>%s</xml>" % xml | null |
177,811 | from _pydevd_bundle.pydevd_constants import ForkSafeLock, get_global_debugger
import os
import sys
from contextlib import contextmanager
class _RedirectionsHolder:
_lock = ForkSafeLock(rlock=True)
_stack_stdout = []
_stack_stderr = []
_pydevd_stdout_redirect_ = None
_pydevd_stderr_redirect_ = None
def end_redirect(std='stdout'):
with _RedirectionsHolder._lock:
if std == 'both':
config_stds = ['stdout', 'stderr']
else:
config_stds = [std]
for std in config_stds:
stack = getattr(_RedirectionsHolder, '_stack_%s' % std)
redirect_info = stack.pop()
setattr(sys, std, redirect_info.original) | null |
177,812 | from _pydevd_bundle.pydevd_comm import get_global_debugger
from _pydev_bundle import pydev_log
class DebugProperty(object):
"""A custom property which allows python property to get
controlled by the debugger and selectively disable/re-enable
the tracing.
"""
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
global_debugger = get_global_debugger()
try:
if global_debugger is not None and global_debugger.disable_property_getter_trace:
global_debugger.disable_tracing()
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
finally:
if global_debugger is not None:
global_debugger.enable_tracing()
def __set__(self, obj, value):
global_debugger = get_global_debugger()
try:
if global_debugger is not None and global_debugger.disable_property_setter_trace:
global_debugger.disable_tracing()
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
finally:
if global_debugger is not None:
global_debugger.enable_tracing()
def __delete__(self, obj):
global_debugger = get_global_debugger()
try:
if global_debugger is not None and global_debugger.disable_property_deleter_trace:
global_debugger.disable_tracing()
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
finally:
if global_debugger is not None:
global_debugger.enable_tracing()
def getter(self, fget):
"""Overriding getter decorator for the property
"""
self.fget = fget
return self
def setter(self, fset):
"""Overriding setter decorator for the property
"""
self.fset = fset
return self
def deleter(self, fdel):
"""Overriding deleter decorator for the property
"""
self.fdel = fdel
return self
def replace_builtin_property(new_property=None):
if new_property is None:
new_property = DebugProperty
original = property
try:
import builtins
builtins.__dict__['property'] = new_property
except:
pydev_log.exception() # @Reimport
return original | null |
177,813 | import sys
import importlib.machinery
import importlib.util
import io
import types
import os
def _run_code(code, run_globals, init_globals=None,
mod_name=None, mod_spec=None,
pkg_name=None, script_name=None):
"""Helper to run code in nominated namespace"""
if init_globals is not None:
run_globals.update(init_globals)
if mod_spec is None:
loader = None
fname = script_name
cached = None
else:
loader = mod_spec.loader
fname = mod_spec.origin
cached = mod_spec.cached
if pkg_name is None:
pkg_name = mod_spec.parent
run_globals.update(__name__=mod_name,
__file__=fname,
__cached__=cached,
__doc__=None,
__loader__=loader,
__package__=pkg_name,
__spec__=mod_spec)
exec(code, run_globals)
return run_globals
def _run_module_code(code, init_globals=None,
mod_name=None, mod_spec=None,
pkg_name=None, script_name=None):
"""Helper to run code in new namespace with sys modified"""
fname = script_name if mod_spec is None else mod_spec.origin
with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname):
mod_globals = temp_module.module.__dict__
_run_code(code, mod_globals, init_globals,
mod_name, mod_spec, pkg_name, script_name)
# Copy the globals of the temporary module, as they
# may be cleared when the temporary module goes away
return mod_globals.copy()
def _get_module_details(mod_name, error=ImportError):
if mod_name.startswith("."):
raise error("Relative module names not supported")
pkg_name, _, _ = mod_name.rpartition(".")
if pkg_name:
# Try importing the parent to avoid catching initialization errors
try:
__import__(pkg_name)
except ImportError as e:
# If the parent or higher ancestor package is missing, let the
# error be raised by find_spec() below and then be caught. But do
# not allow other errors to be caught.
if e.name is None or (e.name != pkg_name and
not pkg_name.startswith(e.name + ".")):
raise
# Warn if the module has already been imported under its normal name
existing = sys.modules.get(mod_name)
if existing is not None and not hasattr(existing, "__path__"):
from warnings import warn
msg = "{mod_name!r} found in sys.modules after import of " \
"package {pkg_name!r}, but prior to execution of " \
"{mod_name!r}; this may result in unpredictable " \
"behaviour".format(mod_name=mod_name, pkg_name=pkg_name)
warn(RuntimeWarning(msg))
try:
spec = importlib.util.find_spec(mod_name)
except (ImportError, AttributeError, TypeError, ValueError) as ex:
# This hack fixes an impedance mismatch between pkgutil and
# importlib, where the latter raises other errors for cases where
# pkgutil previously raised ImportError
msg = "Error while finding module specification for {!r} ({}: {})"
if mod_name.endswith(".py"):
msg += (f". Try using '{mod_name[:-3]}' instead of "
f"'{mod_name}' as the module name.")
raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
if spec is None:
raise error("No module named %s" % mod_name)
if spec.submodule_search_locations is not None:
if mod_name == "__main__" or mod_name.endswith(".__main__"):
raise error("Cannot use package as __main__ module")
try:
pkg_main_name = mod_name + ".__main__"
return _get_module_details(pkg_main_name, error)
except error as e:
if mod_name not in sys.modules:
raise # No module loaded; being a package is irrelevant
raise error(("%s; %r is a package and cannot " +
"be directly executed") % (e, mod_name))
loader = spec.loader
if loader is None:
raise error("%r is a namespace package and cannot be executed"
% mod_name)
try:
code = loader.get_code(mod_name)
except ImportError as e:
raise error(format(e)) from e
if code is None:
raise error("No code object available for %s" % mod_name)
return mod_name, spec, code
The provided code snippet includes necessary dependencies for implementing the `run_module` function. Write a Python function `def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)` to solve the following problem:
Execute a module's code without importing it Returns the resulting top level namespace dictionary
Here is the function:
def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
mod_name, mod_spec, code = _get_module_details(mod_name)
if run_name is None:
run_name = mod_name
if alter_sys:
return _run_module_code(code, init_globals, run_name, mod_spec)
else:
# Leave the sys module alone
return _run_code(code, {}, init_globals, run_name, mod_spec) | Execute a module's code without importing it Returns the resulting top level namespace dictionary |
177,814 | from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, NO_FTRACE,
USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, ForkSafeLock)
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from _pydevd_bundle.pydevd_frame import PyDBFrame, is_unhandled_exception
_global_notify_skipped_step_in = False
_global_notify_skipped_step_in_lock = ForkSafeLock()
def notify_skipped_step_in_because_of_filters(py_db, frame):
global _global_notify_skipped_step_in
with _global_notify_skipped_step_in_lock:
if _global_notify_skipped_step_in:
# Check with lock in place (callers should actually have checked
# before without the lock in place due to performance).
return
_global_notify_skipped_step_in = True
py_db.notify_skipped_step_in_because_of_filters(frame) | null |
177,815 | from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, NO_FTRACE,
USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, ForkSafeLock)
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from _pydevd_bundle.pydevd_frame import PyDBFrame, is_unhandled_exception
def fix_top_level_trace_and_get_trace_func(py_db, frame):
# IFDEF CYTHON
# cdef str filename;
# cdef str name;
# cdef tuple args;
# ENDIF
# Note: this is always the first entry-point in the tracing for any thread.
# After entering here we'll set a new tracing function for this thread
# where more information is cached (and will also setup the tracing for
# frames where we should deal with unhandled exceptions).
thread = None
# Cache the frame which should be traced to deal with unhandled exceptions.
# (i.e.: thread entry-points).
f_unhandled = frame
# print('called at', f_unhandled.f_code.co_name, f_unhandled.f_code.co_filename, f_unhandled.f_code.co_firstlineno)
force_only_unhandled_tracer = False
while f_unhandled is not None:
# name = splitext(basename(f_unhandled.f_code.co_filename))[0]
name = f_unhandled.f_code.co_filename
# basename
i = name.rfind('/')
j = name.rfind('\\')
if j > i:
i = j
if i >= 0:
name = name[i + 1:]
# remove ext
i = name.rfind('.')
if i >= 0:
name = name[:i]
if name == 'threading':
if f_unhandled.f_code.co_name in ('__bootstrap', '_bootstrap'):
# We need __bootstrap_inner, not __bootstrap.
return None, False
elif f_unhandled.f_code.co_name in ('__bootstrap_inner', '_bootstrap_inner'):
# Note: be careful not to use threading.currentThread to avoid creating a dummy thread.
t = f_unhandled.f_locals.get('self')
force_only_unhandled_tracer = True
if t is not None and isinstance(t, threading.Thread):
thread = t
break
elif name == 'pydev_monkey':
if f_unhandled.f_code.co_name == '__call__':
force_only_unhandled_tracer = True
break
elif name == 'pydevd':
if f_unhandled.f_code.co_name in ('run', 'main'):
# We need to get to _exec
return None, False
if f_unhandled.f_code.co_name == '_exec':
force_only_unhandled_tracer = True
break
elif name == 'pydevd_tracing':
return None, False
elif f_unhandled.f_back is None:
break
f_unhandled = f_unhandled.f_back
if thread is None:
# Important: don't call threadingCurrentThread if we're in the threading module
# to avoid creating dummy threads.
if py_db.threading_get_ident is not None:
thread = py_db.threading_active.get(py_db.threading_get_ident())
if thread is None:
return None, False
else:
# Jython does not have threading.get_ident().
thread = py_db.threading_current_thread()
if getattr(thread, 'pydev_do_not_trace', None):
py_db.disable_tracing()
return None, False
try:
additional_info = thread.additional_info
if additional_info is None:
raise AttributeError()
except:
additional_info = py_db.set_additional_thread_info(thread)
# print('enter thread tracer', thread, get_current_thread_id(thread))
args = (py_db, thread, additional_info, global_cache_skips, global_cache_frame_skips)
if f_unhandled is not None:
if f_unhandled.f_back is None and not force_only_unhandled_tracer:
# Happens when we attach to a running program (cannot reuse instance because it's mutable).
top_level_thread_tracer = TopLevelThreadTracerNoBackFrame(ThreadTracer(args), args)
additional_info.top_level_thread_tracer_no_back_frames.append(top_level_thread_tracer) # Hack for cython to keep it alive while the thread is alive (just the method in the SetTrace is not enough).
else:
top_level_thread_tracer = additional_info.top_level_thread_tracer_unhandled
if top_level_thread_tracer is None:
# Stop in some internal place to report about unhandled exceptions
top_level_thread_tracer = TopLevelThreadTracerOnlyUnhandledExceptions(args)
additional_info.top_level_thread_tracer_unhandled = top_level_thread_tracer # Hack for cython to keep it alive while the thread is alive (just the method in the SetTrace is not enough).
# print(' --> found to trace unhandled', f_unhandled.f_code.co_name, f_unhandled.f_code.co_filename, f_unhandled.f_code.co_firstlineno)
f_trace = top_level_thread_tracer.get_trace_dispatch_func()
# IFDEF CYTHON
# f_trace = SafeCallWrapper(f_trace)
# ENDIF
f_unhandled.f_trace = f_trace
if frame is f_unhandled:
return f_trace, False
thread_tracer = additional_info.thread_tracer
if thread_tracer is None or thread_tracer._args[0] is not py_db:
thread_tracer = ThreadTracer(args)
additional_info.thread_tracer = thread_tracer
# IFDEF CYTHON
# return SafeCallWrapper(thread_tracer), True
# ELSE
return thread_tracer, True
def trace_dispatch(py_db, frame, event, arg):
thread_trace_func, apply_to_settrace = py_db.fix_top_level_trace_and_get_trace_func(py_db, frame)
if thread_trace_func is None:
return None if event == 'call' else NO_FTRACE
if apply_to_settrace:
py_db.enable_tracing(thread_trace_func)
return thread_trace_func(frame, event, arg) | null |
177,816 | from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import (get_current_thread_id, NO_FTRACE,
USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, ForkSafeLock)
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from _pydevd_bundle.pydevd_frame import PyDBFrame, is_unhandled_exception
def __call__(self, frame, event, arg):
constructed_tid_to_last_frame[self._args[1].ident] = frame
return _original_call(self, frame, event, arg) | null |
177,817 |
def Exec(exp, global_vars, local_vars=None):
if local_vars is not None:
exec(exp, global_vars, local_vars)
else:
exec(exp, global_vars) | null |
177,818 | import itertools
import json
import linecache
import os
import platform
import sys
from functools import partial
import pydevd_file_utils
from _pydev_bundle import pydev_log
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle._debug_adapter.pydevd_schema import (
CompletionsResponseBody, EvaluateResponseBody, ExceptionOptions,
GotoTargetsResponseBody, ModulesResponseBody, ProcessEventBody,
ProcessEvent, Scope, ScopesResponseBody, SetExpressionResponseBody,
SetVariableResponseBody, SourceBreakpoint, SourceResponseBody,
VariablesResponseBody, SetBreakpointsResponseBody, Response,
Capabilities, PydevdAuthorizeRequest, Request,
StepInTargetsResponseBody, SetFunctionBreakpointsResponseBody, BreakpointEvent,
BreakpointEventBody, InitializedEvent)
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_breakpoints import get_exception_class, FunctionBreakpoint
from _pydevd_bundle.pydevd_comm_constants import (
CMD_PROCESS_EVENT, CMD_RETURN, CMD_SET_NEXT_STATEMENT, CMD_STEP_INTO,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, file_system_encoding,
CMD_STEP_RETURN_MY_CODE, CMD_STEP_RETURN)
from _pydevd_bundle.pydevd_filtering import ExcludeFilter
from _pydevd_bundle.pydevd_json_debug_options import _extract_debug_options, DebugOptions
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_utils import convert_dap_log_message_to_expression, ScopeRequest
from _pydevd_bundle.pydevd_constants import (PY_IMPL_NAME, DebugInfoHolder, PY_VERSION_STR,
PY_IMPL_VERSION_STR, IS_64BIT_PROCESS)
from _pydevd_bundle.pydevd_trace_dispatch import USING_CYTHON
from _pydevd_frame_eval.pydevd_frame_eval_main import USING_FRAME_EVAL
from _pydevd_bundle.pydevd_comm import internal_get_step_in_targets_json
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id
ExcludeFilter = namedtuple('ExcludeFilter', 'name, exclude, is_path')
def _convert_rules_to_exclude_filters(rules, on_error):
exclude_filters = []
if not isinstance(rules, list):
on_error('Invalid "rules" (expected list of dicts). Found: %s' % (rules,))
else:
directory_exclude_filters = []
module_exclude_filters = []
glob_exclude_filters = []
for rule in rules:
if not isinstance(rule, dict):
on_error('Invalid "rules" (expected list of dicts). Found: %s' % (rules,))
continue
include = rule.get('include')
if include is None:
on_error('Invalid "rule" (expected dict with "include"). Found: %s' % (rule,))
continue
path = rule.get('path')
module = rule.get('module')
if path is None and module is None:
on_error('Invalid "rule" (expected dict with "path" or "module"). Found: %s' % (rule,))
continue
if path is not None:
glob_pattern = path
if '*' not in path and '?' not in path:
if os.path.isdir(glob_pattern):
# If a directory was specified, add a '/**'
# to be consistent with the glob pattern required
# by pydevd.
if not glob_pattern.endswith('/') and not glob_pattern.endswith('\\'):
glob_pattern += '/'
glob_pattern += '**'
directory_exclude_filters.append(ExcludeFilter(glob_pattern, not include, True))
else:
glob_exclude_filters.append(ExcludeFilter(glob_pattern, not include, True))
elif module is not None:
module_exclude_filters.append(ExcludeFilter(module, not include, False))
else:
on_error('Internal error: expected path or module to be specified.')
# Note that we have to sort the directory/module exclude filters so that the biggest
# paths match first.
# i.e.: if we have:
# /sub1/sub2/sub3
# a rule with /sub1/sub2 would match before a rule only with /sub1.
directory_exclude_filters = sorted(directory_exclude_filters, key=lambda exclude_filter:-len(exclude_filter.name))
module_exclude_filters = sorted(module_exclude_filters, key=lambda exclude_filter:-len(exclude_filter.name))
exclude_filters = directory_exclude_filters + glob_exclude_filters + module_exclude_filters
return exclude_filters | null |
177,819 | import sys
import traceback
import inspect
import __future__
from _pydev_bundle._pydev_saved_modules import threading
class InteractiveConsole(InteractiveInterpreter):
"""Closely emulate the behavior of the interactive Python interpreter.
This class builds on InteractiveInterpreter and adds prompting
using the familiar sys.ps1 and sys.ps2, and input buffering.
"""
def __init__(self, locals=None, filename="<console>"):
"""Constructor.
The optional locals argument will be passed to the
InteractiveInterpreter base class.
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
InteractiveInterpreter.__init__(self, locals)
self.filename = filename
self.resetbuffer()
def resetbuffer(self):
"""Reset the input buffer."""
self.buffer = []
def interact(self, banner=None, exitmsg=None):
"""Closely emulate the interactive Python console.
The optional banner argument specifies the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
The optional exitmsg argument specifies the exit message
printed when exiting. Pass the empty string to suppress
printing an exit message. If exitmsg is not given or None,
a default message is printed.
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
elif banner:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
if exitmsg is None:
self.write('now exiting %s...\n' % self.__class__.__name__)
elif exitmsg != '':
self.write('%s\n' % exitmsg)
def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more
def raw_input(self, prompt=""):
"""Write a prompt and read a line.
The returned line does not include the trailing newline.
When the user enters the EOF key sequence, EOFError is raised.
The base implementation uses the built-in function
input(); a subclass may replace this with a different
implementation.
"""
return input(prompt)
The provided code snippet includes necessary dependencies for implementing the `interact` function. Write a Python function `def interact(banner=None, readfunc=None, local=None, exitmsg=None)` to solve the following problem:
Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() exitmsg -- passed to InteractiveConsole.interact()
Here is the function:
def interact(banner=None, readfunc=None, local=None, exitmsg=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
exitmsg -- passed to InteractiveConsole.interact()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner, exitmsg) | Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() exitmsg -- passed to InteractiveConsole.interact() |
177,820 | from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \
IS_PY311_OR_GREATER
from _pydev_bundle import pydev_log
import itertools
from typing import Any, Dict
def remove_exception_from_frame(frame):
frame.f_locals.pop('__exception__', None) | null |
177,821 | from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \
IS_PY311_OR_GREATER
from _pydev_bundle import pydev_log
import itertools
from typing import Any, Dict
def cached_call(obj, func, *args):
cached_name = '_cached_' + func.__name__
if not hasattr(obj, cached_name):
setattr(obj, cached_name, func(*args))
return getattr(obj, cached_name) | null |
177,822 | from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \
IS_PY311_OR_GREATER
from _pydev_bundle import pydev_log
import itertools
from typing import Any, Dict
_utf8_with_2_bytes = 0x80
_utf8_with_3_bytes = 0x800
_utf8_with_4_bytes = 0x10000
def _utf8_byte_offset_to_character_offset(s: str, offset: int):
byte_offset = 0
char_offset = 0
for char_offset, character in enumerate(s):
byte_offset += 1
codepoint = ord(character)
if codepoint >= _utf8_with_4_bytes:
byte_offset += 3
elif codepoint >= _utf8_with_3_bytes:
byte_offset += 2
elif codepoint >= _utf8_with_2_bytes:
byte_offset += 1
if byte_offset > offset:
break
else:
char_offset += 1
return char_offset | null |
177,823 | from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \
IS_PY311_OR_GREATER
from _pydev_bundle import pydev_log
import itertools
from typing import Any, Dict
def _extract_caret_anchors_in_bytes_from_line_segment(segment: str):
import ast
try:
segment = segment.encode('utf-8')
except UnicodeEncodeError:
return None
try:
tree = ast.parse(segment)
except SyntaxError:
return None
if len(tree.body) != 1:
return None
statement = tree.body[0]
if isinstance(statement, ast.Expr):
expr = statement.value
if isinstance(expr, ast.BinOp):
operator_str = segment[expr.left.end_col_offset:expr.right.col_offset]
operator_offset = len(operator_str) - len(operator_str.lstrip())
left_anchor = expr.left.end_col_offset + operator_offset
right_anchor = left_anchor + 1
if (
operator_offset + 1 < len(operator_str)
and not operator_str[operator_offset + 1] == ord(b' ')
):
right_anchor += 1
return left_anchor, right_anchor
if isinstance(expr, ast.Subscript):
return expr.value.end_col_offset, expr.slice.end_col_offset + 1
return None | null |
177,824 | from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \
IS_PY311_OR_GREATER
from _pydev_bundle import pydev_log
import itertools
from typing import Any, Dict
class FramesList(object):
def __init__(self):
self._frames = []
# If available, the line number for the frame will be gotten from this dict,
# otherwise frame.f_lineno will be used (needed for unhandled exceptions as
# the place where we report may be different from the place where it's raised).
self.frame_id_to_lineno = {}
self.frame_id_to_line_col_info: Dict[Any, _LineColInfo] = {}
self.exc_type = None
self.exc_desc = None
self.trace_obj = None
# This may be set to set the current frame (for the case where we have
# an unhandled exception where we want to show the root bu we have a different
# executing frame).
self.current_frame = None
# This is to know whether an exception was extracted from a __cause__ or __context__.
self.exc_context_msg = ''
self.chained_frames_list = None
def append(self, frame):
self._frames.append(frame)
def last_frame(self):
return self._frames[-1]
def __len__(self):
return len(self._frames)
def __iter__(self):
return iter(self._frames)
def __repr__(self):
lst = ['FramesList(']
lst.append('\n exc_type: ')
lst.append(str(self.exc_type))
lst.append('\n exc_desc: ')
lst.append(str(self.exc_desc))
lst.append('\n trace_obj: ')
lst.append(str(self.trace_obj))
lst.append('\n current_frame: ')
lst.append(str(self.current_frame))
for frame in self._frames:
lst.append('\n ')
lst.append(repr(frame))
lst.append(',')
if self.chained_frames_list is not None:
lst.append('\n--- Chained ---\n')
lst.append(str(self.chained_frames_list))
lst.append('\n)')
return ''.join(lst)
__str__ = __repr__
def create_frames_list_from_exception_cause(trace_obj, frame, exc_type, exc_desc, memo):
lst = []
msg = '<Unknown context>'
try:
exc_cause = getattr(exc_desc, '__cause__', None)
msg = _cause_message
except Exception:
exc_cause = None
if exc_cause is None:
try:
exc_cause = getattr(exc_desc, '__context__', None)
msg = _context_message
except Exception:
exc_cause = None
if exc_cause is None or id(exc_cause) in memo:
return None
# The traceback module does this, so, let's play safe here too...
memo.add(id(exc_cause))
tb = exc_cause.__traceback__
frames_list = FramesList()
frames_list.exc_type = type(exc_cause)
frames_list.exc_desc = exc_cause
frames_list.trace_obj = tb
frames_list.exc_context_msg = msg
while tb is not None:
# Note: we don't use the actual tb.tb_frame because if the cause of the exception
# uses the same frame object, the id(frame) would be the same and the frame_id_to_lineno
# would be wrong as the same frame needs to appear with 2 different lines.
lst.append((_DummyFrameWrapper(tb.tb_frame, tb.tb_lineno, None), tb.tb_lineno, _get_line_col_info_from_tb(tb)))
tb = tb.tb_next
for tb_frame, tb_lineno, line_col_info in lst:
frames_list.append(tb_frame)
frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno
frames_list.frame_id_to_line_col_info[id(tb_frame)] = line_col_info
return frames_list
if IS_PY311_OR_GREATER:
def _get_line_col_info_from_tb(tb):
positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti)
if positions[0] is None:
return _LineColInfo(tb.tb_lineno, *positions[1:])
else:
return _LineColInfo(*positions)
else:
def _get_line_col_info_from_tb(tb):
# Not available on older versions of Python.
return None
def create_frames_list_from_frame(frame):
lst = FramesList()
while frame is not None:
lst.append(frame)
frame = frame.f_back
return lst
EXCEPTION_TYPE_UNHANDLED = 'UNHANDLED'
EXCEPTION_TYPE_USER_UNHANDLED = 'USER_UNHANDLED'
The provided code snippet includes necessary dependencies for implementing the `create_frames_list_from_traceback` function. Write a Python function `def create_frames_list_from_traceback(trace_obj, frame, exc_type, exc_desc, exception_type=None)` to solve the following problem:
:param trace_obj: This is the traceback from which the list should be created. :param frame: This is the first frame to be considered (i.e.: topmost frame). If None is passed, all the frames from the traceback are shown (so, None should be passed for unhandled exceptions). :param exception_type: If this is an unhandled exception or user unhandled exception, we'll not trim the stack to create from the passed frame, rather, we'll just mark the frame in the frames list.
Here is the function:
def create_frames_list_from_traceback(trace_obj, frame, exc_type, exc_desc, exception_type=None):
'''
:param trace_obj:
This is the traceback from which the list should be created.
:param frame:
This is the first frame to be considered (i.e.: topmost frame). If None is passed, all
the frames from the traceback are shown (so, None should be passed for unhandled exceptions).
:param exception_type:
If this is an unhandled exception or user unhandled exception, we'll not trim the stack to create from the passed
frame, rather, we'll just mark the frame in the frames list.
'''
lst = []
tb = trace_obj
if tb is not None and tb.tb_frame is not None:
f = tb.tb_frame.f_back
while f is not None:
lst.insert(0, (f, f.f_lineno, None))
f = f.f_back
while tb is not None:
lst.append((tb.tb_frame, tb.tb_lineno, _get_line_col_info_from_tb(tb)))
tb = tb.tb_next
frames_list = None
for tb_frame, tb_lineno, line_col_info in reversed(lst):
if frames_list is None and (
(frame is tb_frame) or
(frame is None) or
(exception_type == EXCEPTION_TYPE_USER_UNHANDLED)
):
frames_list = FramesList()
if frames_list is not None:
frames_list.append(tb_frame)
frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno
frames_list.frame_id_to_line_col_info[id(tb_frame)] = line_col_info
if frames_list is None and frame is not None:
# Fallback (shouldn't happen in practice).
pydev_log.info('create_frames_list_from_traceback did not find topmost frame in list.')
frames_list = create_frames_list_from_frame(frame)
frames_list.exc_type = exc_type
frames_list.exc_desc = exc_desc
frames_list.trace_obj = trace_obj
if exception_type == EXCEPTION_TYPE_USER_UNHANDLED:
frames_list.current_frame = frame
elif exception_type == EXCEPTION_TYPE_UNHANDLED:
if len(frames_list) > 0:
frames_list.current_frame = frames_list.last_frame()
curr = frames_list
memo = set()
memo.add(id(exc_desc))
while True:
chained = create_frames_list_from_exception_cause(None, None, None, curr.exc_desc, memo)
if chained is None:
break
else:
curr.chained_frames_list = chained
curr = chained
return frames_list | :param trace_obj: This is the traceback from which the list should be created. :param frame: This is the first frame to be considered (i.e.: topmost frame). If None is passed, all the frames from the traceback are shown (so, None should be passed for unhandled exceptions). :param exception_type: If this is an unhandled exception or user unhandled exception, we'll not trim the stack to create from the passed frame, rather, we'll just mark the frame in the frames list. |
177,825 | import types
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_trace_api
def load_plugins():
plugins = []
if django_debug is not None:
plugins.append(django_debug)
if jinja2_debug is not None:
plugins.append(jinja2_debug)
return plugins | null |
177,826 | import types
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_trace_api
def bind_func_to_method(func, obj, method_name):
bound_method = types.MethodType(func, obj)
setattr(obj, method_name, bound_method)
return bound_method | null |
177,827 | import types
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_trace_api
def create_dispatch(obj, name):
def dispatch(self, *args, **kwargs):
result = None
for p in self.active_plugins:
r = getattr(p, name)(self, *args, **kwargs)
if not result:
result = r
return result
return dispatch | null |
177,828 | import sys
def save_locals(frame):
"""
Copy values from locals_dict into the fast stack slots in the given frame.
Note: the 'save_locals' branch had a different approach wrapping the frame (much more code, but it gives ideas
on how to save things partially, not the 'whole' locals).
"""
if not isinstance(frame, frame_type):
# Fix exception when changing Django variable (receiving DjangoTemplateFrame)
return
if save_locals_impl is not None:
try:
save_locals_impl(frame)
except:
pass
The provided code snippet includes necessary dependencies for implementing the `make_save_locals_impl` function. Write a Python function `def make_save_locals_impl()` to solve the following problem:
Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads.
Here is the function:
def make_save_locals_impl():
"""
Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at
module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger
lock being taken in different order in different threads.
"""
try:
if '__pypy__' in sys.builtin_module_names:
import __pypy__ # @UnresolvedImport
save_locals = __pypy__.locals_to_fast
except:
pass
else:
if '__pypy__' in sys.builtin_module_names:
def save_locals_pypy_impl(frame):
save_locals(frame)
return save_locals_pypy_impl
try:
import ctypes
locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast
except:
pass
else:
def save_locals_ctypes_impl(frame):
locals_to_fast(ctypes.py_object(frame), ctypes.c_int(0))
return save_locals_ctypes_impl
return None | Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads. |
177,829 | import json
import urllib.parse as urllib_parse
def int_parser(s, default_value=0):
try:
return int(s)
except Exception:
return default_value | null |
177,830 | import json
import urllib.parse as urllib_parse
def bool_parser(s):
return s in ("True", "true", "1", True, 1) | null |
177,831 | import json
import urllib.parse as urllib_parse
def unquote(s):
return None if s is None else urllib_parse.unquote(s) | null |
177,832 | import json
import urllib.parse as urllib_parse
def _build_debug_options(flags):
"""Build string representation of debug options from the launch config."""
return ';'.join(DEBUG_OPTIONS_BY_FLAG[flag]
for flag in flags or []
if flag in DEBUG_OPTIONS_BY_FLAG)
def _parse_debug_options(opts):
"""Debug options are semicolon separated key=value pairs
"""
options = {}
if not opts:
return options
for opt in opts.split(';'):
try:
key, value = opt.split('=')
except ValueError:
continue
try:
options[key] = DEBUG_OPTIONS_PARSER[key](value)
except KeyError:
continue
return options
The provided code snippet includes necessary dependencies for implementing the `_extract_debug_options` function. Write a Python function `def _extract_debug_options(opts, flags=None)` to solve the following problem:
Return the debug options encoded in the given value. "opts" is a semicolon-separated string of "key=value" pairs. "flags" is a list of strings. If flags is provided then it is used as a fallback. The values come from the launch config: { type:'python', request:'launch'|'attach', name:'friendly name for debug config', debugOptions:[ 'RedirectOutput', 'Django' ], options:'REDIRECT_OUTPUT=True;DJANGO_DEBUG=True' } Further information can be found here: https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes
Here is the function:
def _extract_debug_options(opts, flags=None):
"""Return the debug options encoded in the given value.
"opts" is a semicolon-separated string of "key=value" pairs.
"flags" is a list of strings.
If flags is provided then it is used as a fallback.
The values come from the launch config:
{
type:'python',
request:'launch'|'attach',
name:'friendly name for debug config',
debugOptions:[
'RedirectOutput', 'Django'
],
options:'REDIRECT_OUTPUT=True;DJANGO_DEBUG=True'
}
Further information can be found here:
https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes
"""
if not opts:
opts = _build_debug_options(flags)
return _parse_debug_options(opts) | Return the debug options encoded in the given value. "opts" is a semicolon-separated string of "key=value" pairs. "flags" is a list of strings. If flags is provided then it is used as a fallback. The values come from the launch config: { type:'python', request:'launch'|'attach', name:'friendly name for debug config', debugOptions:[ 'RedirectOutput', 'Django' ], options:'REDIRECT_OUTPUT=True;DJANGO_DEBUG=True' } Further information can be found here: https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes |
177,833 | import fnmatch
import glob
import os.path
import sys
from _pydev_bundle import pydev_log
import pydevd_file_utils
import json
from collections import namedtuple
from _pydev_bundle._pydev_saved_modules import threading
from pydevd_file_utils import normcase
from _pydevd_bundle.pydevd_constants import USER_CODE_BASENAMES_STARTING_WITH, \
LIBRARY_CODE_BASENAMES_STARTING_WITH, IS_PYPY, IS_WINDOWS
from _pydevd_bundle import pydevd_constants
def _convert_to_str_and_clear_empty(roots):
new_roots = []
for root in roots:
assert isinstance(root, str), '%s not str (found: %s)' % (root, type(root))
if root:
new_roots.append(root)
return new_roots | null |
177,834 | import fnmatch
import glob
import os.path
import sys
from _pydev_bundle import pydev_log
import pydevd_file_utils
import json
from collections import namedtuple
from _pydev_bundle._pydev_saved_modules import threading
from pydevd_file_utils import normcase
from _pydevd_bundle.pydevd_constants import USER_CODE_BASENAMES_STARTING_WITH, \
LIBRARY_CODE_BASENAMES_STARTING_WITH, IS_PYPY, IS_WINDOWS
from _pydevd_bundle import pydevd_constants
def _check_matches(patterns, paths):
def glob_matches_path(path, pattern, sep=os.sep, altsep=os.altsep):
if altsep:
pattern = pattern.replace(altsep, sep)
path = path.replace(altsep, sep)
drive = ''
if len(path) > 1 and path[1] == ':':
drive, path = path[0], path[2:]
if drive and len(pattern) > 1:
if pattern[1] == ':':
if drive.lower() != pattern[0].lower():
return False
pattern = pattern[2:]
patterns = pattern.split(sep)
paths = path.split(sep)
if paths:
if paths[0] == '':
paths = paths[1:]
if patterns:
if patterns[0] == '':
patterns = patterns[1:]
return _check_matches(patterns, paths) | null |
177,835 | from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_extension_utils
from _pydevd_bundle import pydevd_resolver
import sys
from _pydevd_bundle.pydevd_constants import BUILTINS_MODULE_NAME, MAXIMUM_VARIABLE_REPRESENTATION_SIZE, \
RETURN_VALUES_DICT, LOAD_VALUES_ASYNC, DEFAULT_VALUE
from _pydev_bundle.pydev_imports import quote
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider
from _pydevd_bundle.pydevd_utils import isinstance_checked, hasattr_checked, DAPGrouper
from _pydevd_bundle.pydevd_resolver import get_var_scope, MoreItems, MoreItemsRange
from typing import Optional
_IS_JYTHON = sys.platform.startswith("java")
class MoreItemsRange:
def __init__(self, value, from_i, to_i):
self.value = value
self.from_i = from_i
self.to_i = to_i
def get_contents_debug_adapter_protocol(self, _self, fmt=None):
l = len(self.value)
ret = []
format_str = '%0' + str(int(len(str(l - 1)))) + 'd'
if fmt is not None and fmt.get('hex', False):
format_str = '0x%0' + str(int(len(hex(l).lstrip('0x')))) + 'x'
for i, item in enumerate(self.value[self.from_i:self.to_i]):
i += self.from_i
ret.append((format_str % i, item, '[%s]' % i))
return ret
def get_dictionary(self, _self, fmt=None):
dct = {}
for key, obj, _ in self.get_contents_debug_adapter_protocol(self, fmt):
dct[key] = obj
return dct
def resolve(self, attribute):
'''
:param var: that's the original object we're dealing with.
:param attribute: that's the key to resolve
-- either the dict key in get_dictionary or the name in the dap protocol.
'''
return self.value[int(attribute)]
def __eq__(self, o):
return isinstance(o, MoreItemsRange) and self.value is o.value and \
self.from_i == o.from_i and self.to_i == o.to_i
def __str__(self):
return '[%s:%s]' % (self.from_i, self.to_i)
__repr__ = __str__
class MoreItems:
def __init__(self, value, handled_items):
self.value = value
self.handled_items = handled_items
def get_contents_debug_adapter_protocol(self, _self, fmt=None):
total_items = len(self.value)
remaining = total_items - self.handled_items
bucket_size = pydevd_constants.PYDEVD_CONTAINER_BUCKET_SIZE
from_i = self.handled_items
to_i = from_i + min(bucket_size, remaining)
ret = []
while remaining > 0:
remaining -= bucket_size
more_items_range = MoreItemsRange(self.value, from_i, to_i)
ret.append((str(more_items_range), more_items_range, None))
from_i = to_i
to_i = from_i + min(bucket_size, remaining)
return ret
def get_dictionary(self, _self, fmt=None):
dct = {}
for key, obj, _ in self.get_contents_debug_adapter_protocol(self, fmt):
dct[key] = obj
return dct
def resolve(self, attribute):
from_i, to_i = attribute[1:-1].split(':')
from_i = int(from_i)
to_i = int(to_i)
return MoreItemsRange(self.value, from_i, to_i)
def __eq__(self, o):
return isinstance(o, MoreItems) and self.value is o.value
def __str__(self):
return '...'
__repr__ = __str__
class DAPGrouper(object):
'''
Note: this is a helper class to group variables on the debug adapter protocol (DAP). For
the xml protocol the type is just added to each variable and the UI can group/hide it as needed.
'''
SCOPE_SPECIAL_VARS = 'special variables'
SCOPE_PROTECTED_VARS = 'protected variables'
SCOPE_FUNCTION_VARS = 'function variables'
SCOPE_CLASS_VARS = 'class variables'
SCOPES_SORTED = [
SCOPE_SPECIAL_VARS,
SCOPE_PROTECTED_VARS,
SCOPE_FUNCTION_VARS,
SCOPE_CLASS_VARS,
]
__slots__ = ['variable_reference', 'scope', 'contents_debug_adapter_protocol']
def __init__(self, scope):
self.variable_reference = id(self)
self.scope = scope
self.contents_debug_adapter_protocol = []
def get_contents_debug_adapter_protocol(self):
return self.contents_debug_adapter_protocol[:]
def __eq__(self, o):
if isinstance(o, ScopeRequest):
return self.variable_reference == o.variable_reference and self.scope == o.scope
return False
def __ne__(self, o):
return not self == o
def __hash__(self):
return hash((self.variable_reference, self.scope))
def __repr__(self):
return ''
def __str__(self):
return ''
class OrderedDict(dict):
def __init__(self, data=None, **kwargs):
self._keys = self.keys(data, kwargs.get("keys"))
self._default_factory = kwargs.get("default_factory")
if data is None:
dict.__init__(self)
else:
dict.__init__(self, data)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._keys.remove(key)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __iter__(self):
return (key for key in self.keys())
def __missing__(self, key):
if not self._default_factory and key not in self._keys:
raise KeyError()
return self._default_factory()
def __setitem__(self, key, item):
dict.__setitem__(self, key, item)
if key not in self._keys:
self._keys.append(key)
def clear(self):
dict.clear(self)
self._keys.clear()
def copy(self):
d = dict.copy(self)
d._keys = self._keys
return d
def items(self):
# returns iterator under python 3 and list under python 2
return zip(self.keys(), self.values())
def keys(self, data=None, keys=None):
if data:
if keys:
assert isinstance(keys, list)
assert len(data) == len(keys)
return keys
else:
assert (
isinstance(data, dict)
or isinstance(data, OrderedDict)
or isinstance(data, list)
)
if isinstance(data, dict) or isinstance(data, OrderedDict):
return data.keys()
elif isinstance(data, list):
return [key for (key, value) in data]
elif "_keys" in self.__dict__:
return self._keys
else:
return []
def popitem(self):
if not self._keys:
raise KeyError()
key = self._keys.pop()
value = self[key]
del self[key]
return (key, value)
def setdefault(self, key, failobj=None):
dict.setdefault(self, key, failobj)
if key not in self._keys:
self._keys.append(key)
def update(self, data):
dict.update(self, data)
for key in self.keys(data):
if key not in self._keys:
self._keys.append(key)
def values(self):
# returns iterator under python 3
return map(self.get, self._keys)
class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]):
def __init__(self, iterable: Iterable[_T] = ..., maxlen: int = ...) -> None: ...
def maxlen(self) -> Optional[int]: ...
def append(self, x: _T) -> None: ...
def appendleft(self, x: _T) -> None: ...
def clear(self) -> None: ...
def count(self, x: _T) -> int: ...
def extend(self, iterable: Iterable[_T]) -> None: ...
def extendleft(self, iterable: Iterable[_T]) -> None: ...
def pop(self) -> _T: ...
def popleft(self) -> _T: ...
def remove(self, value: _T) -> None: ...
def reverse(self) -> None: ...
def rotate(self, n: int = ...) -> None: ...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[_T]: ...
def __str__(self) -> str: ...
def __hash__(self) -> int: ...
def __getitem__(self, i: int) -> _T: ...
def __setitem__(self, i: int, x: _T) -> None: ...
def __contains__(self, o: _T) -> bool: ...
def __reversed__(self) -> Iterator[_T]: ...
def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ...
def _create_default_type_map():
default_type_map = [
# None means that it should not be treated as a compound variable
# isintance does not accept a tuple on some versions of python, so, we must declare it expanded
(type(None), None,),
(int, None),
(float, None),
(complex, None),
(str, None),
(tuple, pydevd_resolver.tupleResolver),
(list, pydevd_resolver.tupleResolver),
(dict, pydevd_resolver.dictResolver),
]
try:
from collections import OrderedDict
default_type_map.insert(0, (OrderedDict, pydevd_resolver.orderedDictResolver))
# we should put it before dict
except:
pass
try:
default_type_map.append((long, None)) # @UndefinedVariable
except:
pass # not available on all python versions
default_type_map.append((DAPGrouper, pydevd_resolver.dapGrouperResolver))
default_type_map.append((MoreItems, pydevd_resolver.forwardInternalResolverToObject))
default_type_map.append((MoreItemsRange, pydevd_resolver.forwardInternalResolverToObject))
try:
default_type_map.append((set, pydevd_resolver.setResolver))
except:
pass # not available on all python versions
try:
default_type_map.append((frozenset, pydevd_resolver.setResolver))
except:
pass # not available on all python versions
try:
from django.utils.datastructures import MultiValueDict
default_type_map.insert(0, (MultiValueDict, pydevd_resolver.multiValueDictResolver))
# we should put it before dict
except:
pass # django may not be installed
try:
from django.forms import BaseForm
default_type_map.insert(0, (BaseForm, pydevd_resolver.djangoFormResolver))
# we should put it before instance resolver
except:
pass # django may not be installed
try:
from collections import deque
default_type_map.append((deque, pydevd_resolver.dequeResolver))
except:
pass
try:
from ctypes import Array
default_type_map.append((Array, pydevd_resolver.tupleResolver))
except:
pass
if frame_type is not None:
default_type_map.append((frame_type, pydevd_resolver.frameResolver))
if _IS_JYTHON:
from org.python import core # @UnresolvedImport
default_type_map.append((core.PyNone, None))
default_type_map.append((core.PyInteger, None))
default_type_map.append((core.PyLong, None))
default_type_map.append((core.PyFloat, None))
default_type_map.append((core.PyComplex, None))
default_type_map.append((core.PyString, None))
default_type_map.append((core.PyTuple, pydevd_resolver.tupleResolver))
default_type_map.append((core.PyList, pydevd_resolver.tupleResolver))
default_type_map.append((core.PyDictionary, pydevd_resolver.dictResolver))
default_type_map.append((core.PyStringMap, pydevd_resolver.dictResolver))
if hasattr(core, 'PyJavaInstance'):
# Jython 2.5b3 removed it.
default_type_map.append((core.PyJavaInstance, pydevd_resolver.instanceResolver))
return default_type_map | null |
177,836 | from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_extension_utils
from _pydevd_bundle import pydevd_resolver
import sys
from _pydevd_bundle.pydevd_constants import BUILTINS_MODULE_NAME, MAXIMUM_VARIABLE_REPRESENTATION_SIZE, \
RETURN_VALUES_DICT, LOAD_VALUES_ASYNC, DEFAULT_VALUE
from _pydev_bundle.pydev_imports import quote
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider
from _pydevd_bundle.pydevd_utils import isinstance_checked, hasattr_checked, DAPGrouper
from _pydevd_bundle.pydevd_resolver import get_var_scope, MoreItems, MoreItemsRange
from typing import Optional
def var_to_xml(val, name, trim_if_too_big=True, additional_in_xml='', evaluate_full_value=True):
""" single variable or dictionary to xml representation """
type_name, type_qualifier, is_exception_on_eval, resolver, value = get_variable_details(
val, evaluate_full_value)
scope = get_var_scope(name, val, '', True)
try:
name = quote(name, '/>_= ') # TODO: Fix PY-5834 without using quote
except:
pass
xml = '<var name="%s" type="%s" ' % (make_valid_xml_value(name), make_valid_xml_value(type_name))
if type_qualifier:
xml_qualifier = 'qualifier="%s"' % make_valid_xml_value(type_qualifier)
else:
xml_qualifier = ''
if value:
# cannot be too big... communication may not handle it.
if len(value) > MAXIMUM_VARIABLE_REPRESENTATION_SIZE and trim_if_too_big:
value = value[0:MAXIMUM_VARIABLE_REPRESENTATION_SIZE]
value += '...'
xml_value = ' value="%s"' % (make_valid_xml_value(quote(value, '/>_= ')))
else:
xml_value = ''
if is_exception_on_eval:
xml_container = ' isErrorOnEval="True"'
else:
if resolver is not None:
xml_container = ' isContainer="True"'
else:
xml_container = ''
if scope:
return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' scope="', scope, '"', ' />\n'))
else:
return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' />\n'))
def return_values_from_dict_to_xml(return_dict):
res = []
for name, val in return_dict.items():
res.append(var_to_xml(val, name, additional_in_xml=' isRetVal="True"'))
return ''.join(res) | null |
177,837 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
Queue = _queue.Queue
class _ServerHolder:
'''
Helper so that we don't have to use a global here.
'''
SERVER = None
class ServerFacade(object):
def __init__(self, notifications_queue):
self.notifications_queue = notifications_queue
def notifyTestsCollected(self, *args):
self.notifications_queue.put_nowait(ParallelNotification('notifyTestsCollected', args))
def notifyConnected(self, *args):
self.notifications_queue.put_nowait(ParallelNotification('notifyConnected', args))
def notifyTestRunFinished(self, *args):
self.notifications_queue.put_nowait(ParallelNotification('notifyTestRunFinished', args))
def notifyStartTest(self, *args):
self.notifications_queue.put_nowait(ParallelNotification('notifyStartTest', args))
def notifyTest(self, *args):
new_args = []
for arg in args:
new_args.append(_encode_if_needed(arg))
args = tuple(new_args)
self.notifications_queue.put_nowait(ParallelNotification('notifyTest', args))
class ServerComm(threading.Thread):
def __init__(self, notifications_queue, port, daemon=False):
threading.Thread.__init__(self)
self.setDaemon(daemon) # If False, wait for all the notifications to be passed before exiting!
self.finished = False
self.notifications_queue = notifications_queue
from _pydev_bundle import pydev_localhost
# It is necessary to specify an encoding, that matches
# the encoding of all bytes-strings passed into an
# XMLRPC call: "All 8-bit strings in the data structure are assumed to use the
# packet encoding. Unicode strings are automatically converted,
# where necessary."
# Byte strings most likely come from file names.
encoding = file_system_encoding
if encoding == "mbcs":
# Windos symbolic name for the system encoding CP_ACP.
# We need to convert it into a encoding that is recognized by Java.
# Unfortunately this is not always possible. You could use
# GetCPInfoEx and get a name similar to "windows-1251". Then
# you need a table to translate on a best effort basis. Much to complicated.
# ISO-8859-1 is good enough.
encoding = "ISO-8859-1"
self.server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port),
encoding=encoding)
def run(self):
while True:
kill_found = False
commands = []
command = self.notifications_queue.get(block=True)
if isinstance(command, KillServer):
kill_found = True
else:
assert isinstance(command, ParallelNotification)
commands.append(command.to_tuple())
try:
while True:
command = self.notifications_queue.get(block=False) # No block to create a batch.
if isinstance(command, KillServer):
kill_found = True
else:
assert isinstance(command, ParallelNotification)
commands.append(command.to_tuple())
except:
pass # That's OK, we're getting it until it becomes empty so that we notify multiple at once.
if commands:
try:
self.server.notifyCommands(commands)
except:
traceback.print_exc()
if kill_found:
self.finished = True
return
class Null:
"""
Gotten from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
"""
def __init__(self, *args, **kwargs):
return None
def __call__(self, *args, **kwargs):
return self
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, *args, **kwargs):
return self
def __getattr__(self, mname):
if len(mname) > 4 and mname[:2] == '__' and mname[-2:] == '__':
# Don't pretend to implement special method names.
raise AttributeError(mname)
return self
def __setattr__(self, name, value):
return self
def __delattr__(self, name):
return self
def __repr__(self):
return "<Null>"
def __str__(self):
return "Null"
def __len__(self):
return 0
def __getitem__(self):
return self
def __setitem__(self, *args, **kwargs):
pass
def write(self, *args, **kwargs):
pass
def __nonzero__(self):
return 0
def __iter__(self):
return iter(())
def initialize_server(port, daemon=False):
if _ServerHolder.SERVER is None:
if port is not None:
notifications_queue = Queue()
_ServerHolder.SERVER = ServerFacade(notifications_queue)
_ServerHolder.SERVER_COMM = ServerComm(notifications_queue, port, daemon)
_ServerHolder.SERVER_COMM.start()
else:
# Create a null server, so that we keep the interface even without any connection.
_ServerHolder.SERVER = Null()
_ServerHolder.SERVER_COMM = Null()
try:
_ServerHolder.SERVER.notifyConnected()
except:
traceback.print_exc() | null |
177,838 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
class _ServerHolder:
def notifyTestsCollected(tests_count):
assert tests_count is not None
try:
_ServerHolder.SERVER.notifyTestsCollected(tests_count)
except:
traceback.print_exc() | null |
177,839 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
class _ServerHolder:
'''
Helper so that we don't have to use a global here.
'''
SERVER = None
The provided code snippet includes necessary dependencies for implementing the `notifyStartTest` function. Write a Python function `def notifyStartTest(file, test)` to solve the following problem:
@param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1)
Here is the function:
def notifyStartTest(file, test):
'''
@param file: the tests file (c:/temp/test.py)
@param test: the test ran (i.e.: TestCase.test1)
'''
assert file is not None
if test is None:
test = '' # Could happen if we have an import error importing module.
try:
_ServerHolder.SERVER.notifyStartTest(file, test)
except:
traceback.print_exc() | @param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1) |
177,840 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
class _ServerHolder:
'''
Helper so that we don't have to use a global here.
'''
SERVER = None
def _encode_if_needed(obj):
# In the java side we expect strings to be ISO-8859-1 (org.python.pydev.debug.pyunit.PyUnitServer.initializeDispatches().new Dispatch() {...}.getAsStr(Object))
if isinstance(obj, str): # Unicode in py3
return xmlrpclib.Binary(obj.encode('ISO-8859-1', 'xmlcharrefreplace'))
elif isinstance(obj, bytes):
try:
return xmlrpclib.Binary(obj.decode(sys.stdin.encoding).encode('ISO-8859-1', 'xmlcharrefreplace'))
except:
return xmlrpclib.Binary(obj) # bytes already
return obj
The provided code snippet includes necessary dependencies for implementing the `notifyTest` function. Write a Python function `def notifyTest(cond, captured_output, error_contents, file, test, time)` to solve the following problem:
@param cond: ok, fail, error @param captured_output: output captured from stdout @param captured_output: output captured from stderr @param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1) @param time: float with the number of seconds elapsed
Here is the function:
def notifyTest(cond, captured_output, error_contents, file, test, time):
'''
@param cond: ok, fail, error
@param captured_output: output captured from stdout
@param captured_output: output captured from stderr
@param file: the tests file (c:/temp/test.py)
@param test: the test ran (i.e.: TestCase.test1)
@param time: float with the number of seconds elapsed
'''
assert cond is not None
assert captured_output is not None
assert error_contents is not None
assert file is not None
if test is None:
test = '' # Could happen if we have an import error importing module.
assert time is not None
try:
captured_output = _encode_if_needed(captured_output)
error_contents = _encode_if_needed(error_contents)
_ServerHolder.SERVER.notifyTest(cond, captured_output, error_contents, file, test, time)
except:
traceback.print_exc() | @param cond: ok, fail, error @param captured_output: output captured from stdout @param captured_output: output captured from stderr @param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1) @param time: float with the number of seconds elapsed |
177,841 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
class _ServerHolder:
'''
Helper so that we don't have to use a global here.
'''
SERVER = None
def notifyTestRunFinished(total_time):
assert total_time is not None
try:
_ServerHolder.SERVER.notifyTestRunFinished(total_time)
except:
traceback.print_exc() | null |
177,842 | import sys
import threading
import traceback
import warnings
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_imports import xmlrpclib, _queue
from _pydevd_bundle.pydevd_constants import Null
class _ServerHolder:
'''
Helper so that we don't have to use a global here.
'''
SERVER = None
class KillServer(object):
pass
def force_server_kill():
_ServerHolder.SERVER_COMM.notifications_queue.put_nowait(KillServer()) | null |
177,843 | from __future__ import nested_scopes
import fnmatch
import os.path
from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support
from _pydevd_bundle.pydevd_constants import *
import re
import time
class Configuration:
def __init__(
self,
files_or_dirs='',
verbosity=2,
include_tests=None,
tests=None,
port=None,
files_to_tests=None,
jobs=1,
split_jobs='tests',
coverage_output_dir=None,
coverage_include=None,
coverage_output_file=None,
exclude_files=None,
exclude_tests=None,
include_files=None,
django=False,
):
self.files_or_dirs = files_or_dirs
self.verbosity = verbosity
self.include_tests = include_tests
self.tests = tests
self.port = port
self.files_to_tests = files_to_tests
self.jobs = jobs
self.split_jobs = split_jobs
self.django = django
if include_tests:
assert isinstance(include_tests, (list, tuple))
if exclude_files:
assert isinstance(exclude_files, (list, tuple))
if exclude_tests:
assert isinstance(exclude_tests, (list, tuple))
self.exclude_files = exclude_files
self.include_files = include_files
self.exclude_tests = exclude_tests
self.coverage_output_dir = coverage_output_dir
self.coverage_include = coverage_include
self.coverage_output_file = coverage_output_file
def __str__(self):
return '''Configuration
- files_or_dirs: %s
- verbosity: %s
- tests: %s
- port: %s
- files_to_tests: %s
- jobs: %s
- split_jobs: %s
- include_files: %s
- include_tests: %s
- exclude_files: %s
- exclude_tests: %s
- coverage_output_dir: %s
- coverage_include_dir: %s
- coverage_output_file: %s
- django: %s
''' % (
self.files_or_dirs,
self.verbosity,
self.tests,
self.port,
self.files_to_tests,
self.jobs,
self.split_jobs,
self.include_files,
self.include_tests,
self.exclude_files,
self.exclude_tests,
self.coverage_output_dir,
self.coverage_include,
self.coverage_output_file,
self.django,
)
def gnu_getopt(args, shortopts, longopts=[]):
"""getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing options as soon as a non-option argument is
encountered.
If the first character of the option string is `+', or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered.
"""
opts = []
prog_args = []
if type('') == type(longopts):
longopts = [longopts]
else:
longopts = list(longopts)
# Allow options after non-option arguments?
all_options_first = False
if shortopts.startswith('+'):
shortopts = shortopts[1:]
all_options_first = True
while args:
if args[0] == '--':
prog_args += args[1:]
break
if args[0][:2] == '--':
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
elif args[0][:1] == '-':
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
else:
if all_options_first:
prog_args += args
break
else:
prog_args.append(args[0])
args = args[1:]
return opts, prog_args
The provided code snippet includes necessary dependencies for implementing the `parse_cmdline` function. Write a Python function `def parse_cmdline(argv=None)` to solve the following problem:
Parses command line and returns test directories, verbosity, test filter and test suites usage: runfiles.py -v|--verbosity <level> -t|--tests <Test.test1,Test2> dirs|files Multiprocessing options: jobs=number (with the number of jobs to be used to run the tests) split_jobs='module'|'tests' if == module, a given job will always receive all the tests from a module if == tests, the tests will be split independently of their originating module (default) --exclude_files = comma-separated list of patterns with files to exclude (fnmatch style) --include_files = comma-separated list of patterns with files to include (fnmatch style) --exclude_tests = comma-separated list of patterns with test names to exclude (fnmatch style) Note: if --tests is given, --exclude_files, --include_files and --exclude_tests are ignored!
Here is the function:
def parse_cmdline(argv=None):
"""
Parses command line and returns test directories, verbosity, test filter and test suites
usage:
runfiles.py -v|--verbosity <level> -t|--tests <Test.test1,Test2> dirs|files
Multiprocessing options:
jobs=number (with the number of jobs to be used to run the tests)
split_jobs='module'|'tests'
if == module, a given job will always receive all the tests from a module
if == tests, the tests will be split independently of their originating module (default)
--exclude_files = comma-separated list of patterns with files to exclude (fnmatch style)
--include_files = comma-separated list of patterns with files to include (fnmatch style)
--exclude_tests = comma-separated list of patterns with test names to exclude (fnmatch style)
Note: if --tests is given, --exclude_files, --include_files and --exclude_tests are ignored!
"""
if argv is None:
argv = sys.argv
verbosity = 2
include_tests = None
tests = None
port = None
jobs = 1
split_jobs = 'tests'
files_to_tests = {}
coverage_output_dir = None
coverage_include = None
exclude_files = None
exclude_tests = None
include_files = None
django = False
from _pydev_bundle._pydev_getopt import gnu_getopt
optlist, dirs = gnu_getopt(
argv[1:], "",
[
"verbosity=",
"tests=",
"port=",
"config_file=",
"jobs=",
"split_jobs=",
"include_tests=",
"include_files=",
"exclude_files=",
"exclude_tests=",
"coverage_output_dir=",
"coverage_include=",
"django="
]
)
for opt, value in optlist:
if opt in ("-v", "--verbosity"):
verbosity = value
elif opt in ("-p", "--port"):
port = int(value)
elif opt in ("-j", "--jobs"):
jobs = int(value)
elif opt in ("-s", "--split_jobs"):
split_jobs = value
if split_jobs not in ('module', 'tests'):
raise AssertionError('Expected split to be either "module" or "tests". Was :%s' % (split_jobs,))
elif opt in ("-d", "--coverage_output_dir",):
coverage_output_dir = value.strip()
elif opt in ("-i", "--coverage_include",):
coverage_include = value.strip()
elif opt in ("-I", "--include_tests"):
include_tests = value.split(',')
elif opt in ("-E", "--exclude_files"):
exclude_files = value.split(',')
elif opt in ("-F", "--include_files"):
include_files = value.split(',')
elif opt in ("-e", "--exclude_tests"):
exclude_tests = value.split(',')
elif opt in ("-t", "--tests"):
tests = value.split(',')
elif opt in ("--django",):
django = value.strip() in ['true', 'True', '1']
elif opt in ("-c", "--config_file"):
config_file = value.strip()
if os.path.exists(config_file):
f = open(config_file, 'r')
try:
config_file_contents = f.read()
finally:
f.close()
if config_file_contents:
config_file_contents = config_file_contents.strip()
if config_file_contents:
for line in config_file_contents.splitlines():
file_and_test = line.split('|')
if len(file_and_test) == 2:
file, test = file_and_test
if file in files_to_tests:
files_to_tests[file].append(test)
else:
files_to_tests[file] = [test]
else:
sys.stderr.write('Could not find config file: %s\n' % (config_file,))
if type([]) != type(dirs):
dirs = [dirs]
ret_dirs = []
for d in dirs:
if '|' in d:
# paths may come from the ide separated by |
ret_dirs.extend(d.split('|'))
else:
ret_dirs.append(d)
verbosity = int(verbosity)
if tests:
if verbosity > 4:
sys.stdout.write('--tests provided. Ignoring --exclude_files, --exclude_tests and --include_files\n')
exclude_files = exclude_tests = include_files = None
config = Configuration(
ret_dirs,
verbosity,
include_tests,
tests,
port,
files_to_tests,
jobs,
split_jobs,
coverage_output_dir,
coverage_include,
exclude_files=exclude_files,
exclude_tests=exclude_tests,
include_files=include_files,
django=django,
)
if verbosity > 5:
sys.stdout.write(str(config) + '\n')
return config | Parses command line and returns test directories, verbosity, test filter and test suites usage: runfiles.py -v|--verbosity <level> -t|--tests <Test.test1,Test2> dirs|files Multiprocessing options: jobs=number (with the number of jobs to be used to run the tests) split_jobs='module'|'tests' if == module, a given job will always receive all the tests from a module if == tests, the tests will be split independently of their originating module (default) --exclude_files = comma-separated list of patterns with files to exclude (fnmatch style) --include_files = comma-separated list of patterns with files to include (fnmatch style) --exclude_tests = comma-separated list of patterns with test names to exclude (fnmatch style) Note: if --tests is given, --exclude_files, --include_files and --exclude_tests are ignored! |
177,844 | from __future__ import nested_scopes
import fnmatch
import os.path
from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support
from _pydevd_bundle.pydevd_constants import *
import re
import time
DJANGO_TEST_SUITE_RUNNER = None
def get_django_test_suite_runner():
global DJANGO_TEST_SUITE_RUNNER
if DJANGO_TEST_SUITE_RUNNER:
return DJANGO_TEST_SUITE_RUNNER
try:
# django >= 1.8
import django
from django.test.runner import DiscoverRunner
class MyDjangoTestSuiteRunner(DiscoverRunner):
def __init__(self, on_run_suite):
django.setup()
DiscoverRunner.__init__(self)
self.on_run_suite = on_run_suite
def build_suite(self, *args, **kwargs):
pass
def suite_result(self, *args, **kwargs):
pass
def run_suite(self, *args, **kwargs):
self.on_run_suite()
except:
# django < 1.8
try:
from django.test.simple import DjangoTestSuiteRunner
except:
class DjangoTestSuiteRunner:
def __init__(self):
pass
def run_tests(self, *args, **kwargs):
raise AssertionError("Unable to run suite with django.test.runner.DiscoverRunner nor django.test.simple.DjangoTestSuiteRunner because it couldn't be imported.")
class MyDjangoTestSuiteRunner(DjangoTestSuiteRunner):
def __init__(self, on_run_suite):
DjangoTestSuiteRunner.__init__(self)
self.on_run_suite = on_run_suite
def build_suite(self, *args, **kwargs):
pass
def suite_result(self, *args, **kwargs):
pass
def run_suite(self, *args, **kwargs):
self.on_run_suite()
DJANGO_TEST_SUITE_RUNNER = MyDjangoTestSuiteRunner
return DJANGO_TEST_SUITE_RUNNER | null |
177,845 | import os.path
import sys
from _pydevd_bundle.pydevd_constants import Null
def start_coverage_support_from_params(coverage_output_dir, coverage_output_file, jobs, coverage_include):
def start_coverage_support(configuration):
return start_coverage_support_from_params(
configuration.coverage_output_dir,
configuration.coverage_output_file,
configuration.jobs,
configuration.coverage_include,
) | null |
177,846 | from nose.plugins.multiprocess import MultiProcessTestRunner from nose.plugins.base import Plugin
import sys
from _pydev_runfiles import pydev_runfiles_xml_rpc
import time
from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support
from contextlib import contextmanager
from io import StringIO
import traceback
class PydevPlugin(Plugin):
def __init__(self, configuration):
self.configuration = configuration
Plugin.__init__(self)
def begin(self):
# Called before any test is run (it's always called, with multiprocess or not)
self.start_time = time.time()
self.coverage_files, self.coverage = start_coverage_support(self.configuration)
def finalize(self, result):
# Called after all tests are run (it's always called, with multiprocess or not)
self.coverage.stop()
self.coverage.save()
pydev_runfiles_xml_rpc.notifyTestRunFinished('Finished in: %.2f secs.' % (time.time() - self.start_time,))
#===================================================================================================================
# Methods below are not called with multiprocess (so, we monkey-patch MultiProcessTestRunner.consolidate
# so that they're called, but unfortunately we loose some info -- i.e.: the time for each test in this
# process).
#===================================================================================================================
class Sentinel(object):
pass
def _without_user_address(self, test):
# #PyDev-1095: Conflict between address in test and test.address() in PydevPlugin().report_cond()
user_test_instance = test.test
user_address = self.Sentinel
user_class_address = self.Sentinel
try:
if 'address' in user_test_instance.__dict__:
user_address = user_test_instance.__dict__.pop('address')
except:
# Just ignore anything here.
pass
try:
user_class_address = user_test_instance.__class__.address
del user_test_instance.__class__.address
except:
# Just ignore anything here.
pass
try:
yield
finally:
if user_address is not self.Sentinel:
user_test_instance.__dict__['address'] = user_address
if user_class_address is not self.Sentinel:
user_test_instance.__class__.address = user_class_address
def _get_test_address(self, test):
try:
if hasattr(test, 'address'):
with self._without_user_address(test):
address = test.address()
# test.address() is something as:
# ('D:\\workspaces\\temp\\test_workspace\\pytesting1\\src\\mod1\\hello.py', 'mod1.hello', 'TestCase.testMet1')
#
# and we must pass: location, test
# E.g.: ['D:\\src\\mod1\\hello.py', 'TestCase.testMet1']
address = address[0], address[2]
else:
# multiprocess
try:
address = test[0], test[1]
except TypeError:
# It may be an error at setup, in which case it's not really a test, but a Context object.
f = test.context.__file__
if f.endswith('.pyc'):
f = f[:-1]
elif f.endswith('$py.class'):
f = f[:-len('$py.class')] + '.py'
address = f, '?'
except:
sys.stderr.write("PyDev: Internal pydev error getting test address. Please report at the pydev bug tracker\n")
traceback.print_exc()
sys.stderr.write("\n\n\n")
address = '?', '?'
return address
def report_cond(self, cond, test, captured_output, error=''):
'''
'''
address = self._get_test_address(test)
error_contents = self.get_io_from_error(error)
try:
time_str = '%.2f' % (time.time() - test._pydev_start_time)
except:
time_str = '?'
pydev_runfiles_xml_rpc.notifyTest(cond, captured_output, error_contents, address[0], address[1], time_str)
def startTest(self, test):
test._pydev_start_time = time.time()
file, test = self._get_test_address(test)
pydev_runfiles_xml_rpc.notifyStartTest(file, test)
def get_io_from_error(self, err):
if type(err) == type(()):
if len(err) != 3:
if len(err) == 2:
return err[1] # multiprocess
s = StringIO()
etype, value, tb = err
if isinstance(value, str):
return value
traceback.print_exception(etype, value, tb, file=s)
return s.getvalue()
return err
def get_captured_output(self, test):
if hasattr(test, 'capturedOutput') and test.capturedOutput:
return test.capturedOutput
return ''
def addError(self, test, err):
self.report_cond(
'error',
test,
self.get_captured_output(test),
err,
)
def addFailure(self, test, err):
self.report_cond(
'fail',
test,
self.get_captured_output(test),
err,
)
def addSuccess(self, test):
self.report_cond(
'ok',
test,
self.get_captured_output(test),
'',
)
PYDEV_NOSE_PLUGIN_SINGLETON = None
def start_pydev_nose_plugin_singleton(configuration):
global PYDEV_NOSE_PLUGIN_SINGLETON
PYDEV_NOSE_PLUGIN_SINGLETON = PydevPlugin(configuration)
return PYDEV_NOSE_PLUGIN_SINGLETON | null |
177,847 | from nose.plugins.multiprocess import MultiProcessTestRunner from nose.plugins.base import Plugin
import sys
from _pydev_runfiles import pydev_runfiles_xml_rpc
import time
from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support
from contextlib import contextmanager
from io import StringIO
import traceback
PYDEV_NOSE_PLUGIN_SINGLETON = None
original = MultiProcessTestRunner.consolidate
The provided code snippet includes necessary dependencies for implementing the `new_consolidate` function. Write a Python function `def new_consolidate(self, result, batch_result)` to solve the following problem:
Used so that it can work with the multiprocess plugin. Monkeypatched because nose seems a bit unsupported at this time (ideally the plugin would have this support by default).
Here is the function:
def new_consolidate(self, result, batch_result):
'''
Used so that it can work with the multiprocess plugin.
Monkeypatched because nose seems a bit unsupported at this time (ideally
the plugin would have this support by default).
'''
ret = original(self, result, batch_result)
parent_frame = sys._getframe().f_back
# addr is something as D:\pytesting1\src\mod1\hello.py:TestCase.testMet4
# so, convert it to what report_cond expects
addr = parent_frame.f_locals['addr']
i = addr.rindex(':')
addr = [addr[:i], addr[i + 1:]]
output, testsRun, failures, errors, errorClasses = batch_result
if failures or errors:
for failure in failures:
PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('fail', addr, output, failure)
for error in errors:
PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('error', addr, output, error)
else:
PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('ok', addr, output)
return ret | Used so that it can work with the multiprocess plugin. Monkeypatched because nose seems a bit unsupported at this time (ideally the plugin would have this support by default). |
177,848 | from _pydev_bundle.pydev_imports import xmlrpclib, _queue
import traceback
import sys
from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support_from_params
import threading
class KillServer(object):
pass
class ServerComm(threading.Thread):
def __init__(self, job_id, server):
self.notifications_queue = Queue()
threading.Thread.__init__(self)
self.setDaemon(False) #Wait for all the notifications to be passed before exiting!
assert job_id is not None
assert port is not None
self.job_id = job_id
self.finished = False
self.server = server
def run(self):
while True:
kill_found = False
commands = []
command = self.notifications_queue.get(block=True)
if isinstance(command, KillServer):
kill_found = True
else:
assert isinstance(command, ParallelNotification)
commands.append(command.to_tuple())
try:
while True:
command = self.notifications_queue.get(block=False) #No block to create a batch.
if isinstance(command, KillServer):
kill_found = True
else:
assert isinstance(command, ParallelNotification)
commands.append(command.to_tuple())
except:
pass #That's OK, we're getting it until it becomes empty so that we notify multiple at once.
if commands:
try:
#Batch notification.
self.server.lock.acquire()
try:
self.server.notifyCommands(self.job_id, commands)
finally:
self.server.lock.release()
except:
traceback.print_exc()
if kill_found:
self.finished = True
return
class ServerFacade(object):
def __init__(self, notifications_queue):
self.notifications_queue = notifications_queue
def notifyTestsCollected(self, *args, **kwargs):
pass #This notification won't be passed
def notifyTestRunFinished(self, *args, **kwargs):
pass #This notification won't be passed
def notifyStartTest(self, *args, **kwargs):
self.notifications_queue.put_nowait(ParallelNotification('notifyStartTest', args, kwargs))
def notifyTest(self, *args, **kwargs):
self.notifications_queue.put_nowait(ParallelNotification('notifyTest', args, kwargs))
def start_coverage_support_from_params(coverage_output_dir, coverage_output_file, jobs, coverage_include):
coverage_files = []
coverage_instance = Null()
if coverage_output_dir or coverage_output_file:
try:
import coverage #@UnresolvedImport
except:
sys.stderr.write('Error: coverage module could not be imported\n')
sys.stderr.write('Please make sure that the coverage module (http://nedbatchelder.com/code/coverage/)\n')
sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,))
import traceback;traceback.print_exc()
else:
if coverage_output_dir:
if not os.path.exists(coverage_output_dir):
sys.stderr.write('Error: directory for coverage output (%s) does not exist.\n' % (coverage_output_dir,))
elif not os.path.isdir(coverage_output_dir):
sys.stderr.write('Error: expected (%s) to be a directory.\n' % (coverage_output_dir,))
else:
n = jobs
if n <= 0:
n += 1
n += 1 #Add 1 more for the current process (which will do the initial import).
coverage_files = get_coverage_files(coverage_output_dir, n)
os.environ['COVERAGE_FILE'] = coverage_files.pop(0)
coverage_instance = coverage.coverage(source=[coverage_include])
coverage_instance.start()
elif coverage_output_file:
#Client of parallel run.
os.environ['COVERAGE_FILE'] = coverage_output_file
coverage_instance = coverage.coverage(source=[coverage_include])
coverage_instance.start()
return coverage_files, coverage_instance
def run_client(job_id, port, verbosity, coverage_output_file, coverage_include):
job_id = int(job_id)
from _pydev_bundle import pydev_localhost
server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port))
server.lock = threading.Lock()
server_comm = ServerComm(job_id, server)
server_comm.start()
try:
server_facade = ServerFacade(server_comm.notifications_queue)
from _pydev_runfiles import pydev_runfiles
from _pydev_runfiles import pydev_runfiles_xml_rpc
pydev_runfiles_xml_rpc.set_server(server_facade)
#Starts None and when the 1st test is gotten, it's started (because a server may be initiated and terminated
#before receiving any test -- which would mean a different process got all the tests to run).
coverage = None
try:
tests_to_run = [1]
while tests_to_run:
#Investigate: is it dangerous to use the same xmlrpclib server from different threads?
#It seems it should be, as it creates a new connection for each request...
server.lock.acquire()
try:
tests_to_run = server.GetTestsToRun(job_id)
finally:
server.lock.release()
if not tests_to_run:
break
if coverage is None:
_coverage_files, coverage = start_coverage_support_from_params(
None, coverage_output_file, 1, coverage_include)
files_to_tests = {}
for test in tests_to_run:
filename_and_test = test.split('|')
if len(filename_and_test) == 2:
files_to_tests.setdefault(filename_and_test[0], []).append(filename_and_test[1])
configuration = pydev_runfiles.Configuration(
'',
verbosity,
None,
None,
None,
files_to_tests,
1, #Always single job here
None,
#The coverage is handled in this loop.
coverage_output_file=None,
coverage_include=None,
)
test_runner = pydev_runfiles.PydevTestRunner(configuration)
sys.stdout.flush()
test_runner.run_tests(handle_coverage=False)
finally:
if coverage is not None:
coverage.stop()
coverage.save()
except:
traceback.print_exc()
server_comm.notifications_queue.put_nowait(KillServer()) | null |
177,849 | import unittest
from _pydev_bundle._pydev_saved_modules import thread
import queue as Queue
from _pydev_runfiles import pydev_runfiles_xml_rpc
import time
import os
import threading
import sys
def flatten_test_suite(test_suite, ret):
if isinstance(test_suite, unittest.TestSuite):
for t in test_suite._tests:
flatten_test_suite(t, ret)
elif isinstance(test_suite, unittest.TestCase):
ret.append(test_suite)
class CommunicationThread(threading.Thread):
def __init__(self, tests_queue):
threading.Thread.__init__(self)
self.daemon = True
self.queue = tests_queue
self.finished = False
from _pydev_bundle.pydev_imports import SimpleXMLRPCServer
from _pydev_bundle import pydev_localhost
# Create server
server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), 0), logRequests=False)
server.register_function(self.GetTestsToRun)
server.register_function(self.notifyStartTest)
server.register_function(self.notifyTest)
server.register_function(self.notifyCommands)
self.port = server.socket.getsockname()[1]
self.server = server
def GetTestsToRun(self, job_id):
'''
Each entry is a string in the format: filename|Test.testName
'''
try:
ret = self.queue.get(block=False)
return ret
except: # Any exception getting from the queue (empty or not) means we finished our work on providing the tests.
self.finished = True
return []
def notifyCommands(self, job_id, commands):
# Batch notification.
for command in commands:
getattr(self, command[0])(job_id, *command[1], **command[2])
return True
def notifyStartTest(self, job_id, *args, **kwargs):
pydev_runfiles_xml_rpc.notifyStartTest(*args, **kwargs)
return True
def notifyTest(self, job_id, *args, **kwargs):
pydev_runfiles_xml_rpc.notifyTest(*args, **kwargs)
return True
def shutdown(self):
if hasattr(self.server, 'shutdown'):
self.server.shutdown()
else:
self._shutdown = True
def run(self):
if hasattr(self.server, 'shutdown'):
self.server.serve_forever()
else:
self._shutdown = False
while not self._shutdown:
self.server.handle_request()
class ClientThread(threading.Thread):
def __init__(self, job_id, port, verbosity, coverage_output_file=None, coverage_include=None):
threading.Thread.__init__(self)
self.daemon = True
self.port = port
self.job_id = job_id
self.verbosity = verbosity
self.finished = False
self.coverage_output_file = coverage_output_file
self.coverage_include = coverage_include
def _reader_thread(self, pipe, target):
while True:
target.write(pipe.read(1))
def run(self):
try:
from _pydev_runfiles import pydev_runfiles_parallel_client
# TODO: Support Jython:
#
# For jython, instead of using sys.executable, we should use:
# r'D:\bin\jdk_1_5_09\bin\java.exe',
# '-classpath',
# 'D:/bin/jython-2.2.1/jython.jar',
# 'org.python.util.jython',
args = [
sys.executable,
pydev_runfiles_parallel_client.__file__,
str(self.job_id),
str(self.port),
str(self.verbosity),
]
if self.coverage_output_file and self.coverage_include:
args.append(self.coverage_output_file)
args.append(self.coverage_include)
import subprocess
if False:
proc = subprocess.Popen(args, env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
thread.start_new_thread(self._reader_thread, (proc.stdout, sys.stdout))
thread.start_new_thread(target=self._reader_thread, args=(proc.stderr, sys.stderr))
else:
proc = subprocess.Popen(args, env=os.environ, shell=False)
proc.wait()
finally:
self.finished = True
The provided code snippet includes necessary dependencies for implementing the `execute_tests_in_parallel` function. Write a Python function `def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, coverage_include)` to solve the following problem:
@param tests: list(PydevTestSuite) A list with the suites to be run @param split: str Either 'module' or the number of tests that should be run in each batch @param coverage_files: list(file) A list with the files that should be used for giving coverage information (if empty, coverage information should not be gathered). @param coverage_include: str The pattern that should be included in the coverage. @return: bool Returns True if the tests were actually executed in parallel. If the tests were not executed because only 1 should be used (e.g.: 2 jobs were requested for running 1 test), False will be returned and no tests will be run. It may also return False if in debug mode (in which case, multi-processes are not accepted)
Here is the function:
def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, coverage_include):
'''
@param tests: list(PydevTestSuite)
A list with the suites to be run
@param split: str
Either 'module' or the number of tests that should be run in each batch
@param coverage_files: list(file)
A list with the files that should be used for giving coverage information (if empty, coverage information
should not be gathered).
@param coverage_include: str
The pattern that should be included in the coverage.
@return: bool
Returns True if the tests were actually executed in parallel. If the tests were not executed because only 1
should be used (e.g.: 2 jobs were requested for running 1 test), False will be returned and no tests will be
run.
It may also return False if in debug mode (in which case, multi-processes are not accepted)
'''
try:
from _pydevd_bundle.pydevd_comm import get_global_debugger
if get_global_debugger() is not None:
return False
except:
pass # Ignore any error here.
# This queue will receive the tests to be run. Each entry in a queue is a list with the tests to be run together When
# split == 'tests', each list will have a single element, when split == 'module', each list will have all the tests
# from a given module.
tests_queue = []
queue_elements = []
if split == 'module':
module_to_tests = {}
for test in tests:
lst = []
flatten_test_suite(test, lst)
for test in lst:
key = (test.__pydev_pyfile__, test.__pydev_module_name__)
module_to_tests.setdefault(key, []).append(test)
for key, tests in module_to_tests.items():
queue_elements.append(tests)
if len(queue_elements) < jobs:
# Don't create jobs we will never use.
jobs = len(queue_elements)
elif split == 'tests':
for test in tests:
lst = []
flatten_test_suite(test, lst)
for test in lst:
queue_elements.append([test])
if len(queue_elements) < jobs:
# Don't create jobs we will never use.
jobs = len(queue_elements)
else:
raise AssertionError('Do not know how to handle: %s' % (split,))
for test_cases in queue_elements:
test_queue_elements = []
for test_case in test_cases:
try:
test_name = test_case.__class__.__name__ + "." + test_case._testMethodName
except AttributeError:
# Support for jython 2.1 (__testMethodName is pseudo-private in the test case)
test_name = test_case.__class__.__name__ + "." + test_case._TestCase__testMethodName
test_queue_elements.append(test_case.__pydev_pyfile__ + '|' + test_name)
tests_queue.append(test_queue_elements)
if jobs < 2:
return False
sys.stdout.write('Running tests in parallel with: %s jobs.\n' % (jobs,))
queue = Queue.Queue()
for item in tests_queue:
queue.put(item, block=False)
providers = []
clients = []
for i in range(jobs):
test_cases_provider = CommunicationThread(queue)
providers.append(test_cases_provider)
test_cases_provider.start()
port = test_cases_provider.port
if coverage_files:
clients.append(ClientThread(i, port, verbosity, coverage_files.pop(0), coverage_include))
else:
clients.append(ClientThread(i, port, verbosity))
for client in clients:
client.start()
client_alive = True
while client_alive:
client_alive = False
for client in clients:
# Wait for all the clients to exit.
if not client.finished:
client_alive = True
time.sleep(.2)
break
for provider in providers:
provider.shutdown()
return True | @param tests: list(PydevTestSuite) A list with the suites to be run @param split: str Either 'module' or the number of tests that should be run in each batch @param coverage_files: list(file) A list with the files that should be used for giving coverage information (if empty, coverage information should not be gathered). @param coverage_include: str The pattern that should be included in the coverage. @return: bool Returns True if the tests were actually executed in parallel. If the tests were not executed because only 1 should be used (e.g.: 2 jobs were requested for running 1 test), False will be returned and no tests will be run. It may also return False if in debug mode (in which case, multi-processes are not accepted) |
177,850 | import sys
def dict_contains(d, key):
return d.has_key(key) | null |
177,852 | import sys
if sys.version_info[0] < 3:
try:
#Redefine input and raw_input only after the original sitecustomize was executed
#(because otherwise, the original raw_input and input would still not be defined)
import __builtin__
original_raw_input = __builtin__.raw_input
original_input = __builtin__.input
raw_input.__doc__ = original_raw_input.__doc__
input.__doc__ = original_input.__doc__
__builtin__.raw_input = raw_input
__builtin__.input = input
except:
#Don't report errors at this stage
if DEBUG:
import traceback;traceback.print_exc() #@Reimport
else:
try:
import builtins #Python 3.0 does not have the __builtin__ module @UnresolvedImport
original_input = builtins.input
input.__doc__ = original_input.__doc__
builtins.input = input
except:
#Don't report errors at this stage
if DEBUG:
import traceback;traceback.print_exc() #@Reimport
def install_breakpointhook():
def custom_sitecustomize_breakpointhook(*args, **kwargs):
import os
hookname = os.getenv('PYTHONBREAKPOINT')
if (
hookname is not None
and len(hookname) > 0
and hasattr(sys, '__breakpointhook__')
and sys.__breakpointhook__ != custom_sitecustomize_breakpointhook
):
sys.__breakpointhook__(*args, **kwargs)
else:
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import pydevd
kwargs.setdefault('stop_at_frame', sys._getframe().f_back)
pydevd.settrace(*args, **kwargs)
if sys.version_info[0:2] >= (3, 7):
# There are some choices on how to provide the breakpoint hook. Namely, we can provide a
# PYTHONBREAKPOINT which provides the import path for a method to be executed or we
# can override sys.breakpointhook.
# pydevd overrides sys.breakpointhook instead of providing an environment variable because
# it's possible that the debugger starts the user program but is not available in the
# PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace).
# Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided
# by someone else, it'd still work).
sys.breakpointhook = custom_sitecustomize_breakpointhook
else:
if sys.version_info[0] >= 3:
import builtins as __builtin__ # Py3
else:
import __builtin__
# In older versions, breakpoint() isn't really available, so, install the hook directly
# in the builtins.
__builtin__.breakpoint = custom_sitecustomize_breakpointhook
sys.__breakpointhook__ = custom_sitecustomize_breakpointhook | null |
177,853 | import sys
if sys.version_info[0] < 3:
try:
#Redefine input and raw_input only after the original sitecustomize was executed
#(because otherwise, the original raw_input and input would still not be defined)
import __builtin__
original_raw_input = __builtin__.raw_input
original_input = __builtin__.input
def raw_input(prompt=''):
#the original raw_input would only remove a trailing \n, so, at
#this point if we had a \r\n the \r would remain (which is valid for eclipse)
#so, let's remove the remaining \r which python didn't expect.
ret = original_raw_input(prompt)
if ret.endswith('\r'):
return ret[:-1]
return ret
raw_input.__doc__ = original_raw_input.__doc__
input.__doc__ = original_input.__doc__
__builtin__.raw_input = raw_input
__builtin__.input = input
except:
#Don't report errors at this stage
if DEBUG:
import traceback;traceback.print_exc() #@Reimport
else:
try:
import builtins #Python 3.0 does not have the __builtin__ module @UnresolvedImport
original_input = builtins.input
input.__doc__ = original_input.__doc__
builtins.input = input
except:
#Don't report errors at this stage
if DEBUG:
import traceback;traceback.print_exc() #@Reimport
def input(prompt=''):
#input must also be rebinded for using the new raw_input defined
return eval(raw_input(prompt)) | null |
177,854 | import sys
def input(prompt=''):
#the original input would only remove a trailing \n, so, at
#this point if we had a \r\n the \r would remain (which is valid for eclipse)
#so, let's remove the remaining \r which python didn't expect.
ret = original_input(prompt)
if ret.endswith('\r'):
return ret[:-1]
return ret | null |
177,855 | import sys
def fix_get_pass():
try:
import getpass
except ImportError:
return #If we can't import it, we can't fix it
import warnings
fallback = getattr(getpass, 'fallback_getpass', None) # >= 2.6
if not fallback:
fallback = getpass.default_getpass # <= 2.5
getpass.getpass = fallback
if hasattr(getpass, 'GetPassWarning'):
warnings.simplefilter("ignore", category=getpass.GetPassWarning) | null |
177,856 | def is_valid_py_file(path):
'''
Checks whether the file can be read by the coverage module. This is especially
needed for .pyx files and .py files with syntax errors.
'''
import os
is_valid = False
if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx':
try:
with open(path, 'rb') as f:
compile(f.read(), path, 'exec')
is_valid = True
except:
pass
return is_valid
def execute():
import os
import sys
files = None
if 'combine' not in sys.argv:
if '--pydev-analyze' in sys.argv:
# Ok, what we want here is having the files passed through stdin (because
# there may be too many files for passing in the command line -- we could
# just pass a dir and make the find files here, but as that's already
# given in the java side, let's just gather that info here).
sys.argv.remove('--pydev-analyze')
s = input()
s = s.replace('\r', '')
s = s.replace('\n', '')
files = []
invalid_files = []
for v in s.split('|'):
if is_valid_py_file(v):
files.append(v)
else:
invalid_files.append(v)
if invalid_files:
sys.stderr.write('Invalid files not passed to coverage: %s\n'
% ', '.join(invalid_files))
# Note that in this case we'll already be in the working dir with the coverage files,
# so, the coverage file location is not passed.
else:
# For all commands, the coverage file is configured in pydev, and passed as the first
# argument in the command line, so, let's make sure this gets to the coverage module.
os.environ['COVERAGE_FILE'] = sys.argv[1]
del sys.argv[1]
try:
import coverage # @UnresolvedImport
except:
sys.stderr.write('Error: coverage module could not be imported\n')
sys.stderr.write('Please make sure that the coverage module '
'(http://nedbatchelder.com/code/coverage/)\n')
sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,))
import traceback;traceback.print_exc()
return
if hasattr(coverage, '__version__'):
version = tuple(map(int, coverage.__version__.split('.')[:2]))
if version < (4, 3):
sys.stderr.write('Error: minimum supported coverage version is 4.3.'
'\nFound: %s\nLocation: %s\n'
% ('.'.join(str(x) for x in version), coverage.__file__))
sys.exit(1)
else:
sys.stderr.write('Warning: Could not determine version of python module coverage.'
'\nEnsure coverage version is >= 4.3\n')
from coverage.cmdline import main # @UnresolvedImport
if files is not None:
sys.argv.append('xml')
sys.argv += files
main() | null |
177,857 | import sys
if sys.version_info[:2] < (3, 6):
raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.')
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
def settrace(
host=None,
stdout_to_server=False,
stderr_to_server=False,
port=5678,
suspend=True,
trace_only_current_thread=False,
overwrite_prev_trace=False,
patch_multiprocessing=False,
stop_at_frame=None,
block_until_connected=True,
wait_for_ready_to_run=True,
dont_trace_start_patterns=(),
dont_trace_end_patterns=(),
access_token=None,
client_access_token=None,
notify_stdin=True,
**kwargs
):
def install_breakpointhook(pydevd_breakpointhook=None):
if pydevd_breakpointhook is None:
def pydevd_breakpointhook(*args, **kwargs):
hookname = os.getenv('PYTHONBREAKPOINT')
if (
hookname is not None
and len(hookname) > 0
and hasattr(sys, '__breakpointhook__')
and sys.__breakpointhook__ != pydevd_breakpointhook
):
sys.__breakpointhook__(*args, **kwargs)
else:
settrace(*args, **kwargs)
if sys.version_info[0:2] >= (3, 7):
# There are some choices on how to provide the breakpoint hook. Namely, we can provide a
# PYTHONBREAKPOINT which provides the import path for a method to be executed or we
# can override sys.breakpointhook.
# pydevd overrides sys.breakpointhook instead of providing an environment variable because
# it's possible that the debugger starts the user program but is not available in the
# PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace).
# Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided
# by someone else, it'd still work).
sys.breakpointhook = pydevd_breakpointhook
else:
if sys.version_info[0] >= 3:
import builtins as __builtin__ # Py3 noqa
else:
import __builtin__ # noqa
# In older versions, breakpoint() isn't really available, so, install the hook directly
# in the builtins.
__builtin__.breakpoint = pydevd_breakpointhook
sys.__breakpointhook__ = pydevd_breakpointhook | null |
177,858 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
The provided code snippet includes necessary dependencies for implementing the `add_dap_messages_listener` function. Write a Python function `def add_dap_messages_listener(dap_messages_listener)` to solve the following problem:
Adds a listener for the DAP (debug adapter protocol) messages. :type dap_messages_listener: IDAPMessagesListener :note: messages from the xml backend are not notified through this API. :note: the notifications are sent from threads and they are not synchronized (so, it's possible that a message is sent and received from different threads at the same time).
Here is the function:
def add_dap_messages_listener(dap_messages_listener):
'''
Adds a listener for the DAP (debug adapter protocol) messages.
:type dap_messages_listener: IDAPMessagesListener
:note: messages from the xml backend are not notified through this API.
:note: the notifications are sent from threads and they are not synchronized (so,
it's possible that a message is sent and received from different threads at the same time).
'''
py_db = get_global_debugger()
if py_db is None:
raise AssertionError('PyDB is still not setup.')
py_db.add_dap_messages_listener(dap_messages_listener) | Adds a listener for the DAP (debug adapter protocol) messages. :type dap_messages_listener: IDAPMessagesListener :note: messages from the xml backend are not notified through this API. :note: the notifications are sent from threads and they are not synchronized (so, it's possible that a message is sent and received from different threads at the same time). |
177,859 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
The provided code snippet includes necessary dependencies for implementing the `send_json_message` function. Write a Python function `def send_json_message(msg)` to solve the following problem:
API to send some custom json message. :param dict|pydevd_schema.BaseSchema msg: The custom message to be sent. :return bool: True if the message was added to the queue to be sent and False otherwise.
Here is the function:
def send_json_message(msg):
'''
API to send some custom json message.
:param dict|pydevd_schema.BaseSchema msg:
The custom message to be sent.
:return bool:
True if the message was added to the queue to be sent and False otherwise.
'''
py_db = get_global_debugger()
if py_db is None:
return False
writer = py_db.writer
if writer is None:
return False
cmd = NetCommand(-1, 0, msg, is_json=True)
writer.add_command(cmd)
return True | API to send some custom json message. :param dict|pydevd_schema.BaseSchema msg: The custom message to be sent. :return bool: True if the message was added to the queue to be sent and False otherwise. |
177,860 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT)
pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__))
pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
def dump_threads(stream=None):
'''
Helper to dump thread info (default is printing to stderr).
'''
pydevd_utils.dump_threads(stream)
def mark_as_pydevd_daemon_thread(thread):
if not IS_JYTHON and not IS_IRONPYTHON and PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS:
global _patched_threading_to_hide_pydevd_threads
if not _patched_threading_to_hide_pydevd_threads:
# When we mark the first thread as a pydevd daemon thread, we also change the threading
# functions to hide pydevd threads.
# Note: we don't just "hide" the pydevd threads from the threading module by not using it
# (i.e.: just using the `thread.start_new_thread` instead of `threading.Thread`)
# because there's 1 thread (the `CheckAliveThread`) which is a pydevd thread but
# isn't really a daemon thread (so, we need CPython to wait on it for shutdown,
# in which case it needs to be in `threading` and the patching would be needed anyways).
_patched_threading_to_hide_pydevd_threads = True
try:
_patch_threading_to_hide_pydevd_threads()
except:
pydev_log.exception('Error applying patching to hide pydevd threads.')
thread.pydev_do_not_trace = True
thread.is_pydev_daemon_thread = True
thread.daemon = True
The provided code snippet includes necessary dependencies for implementing the `start_dump_threads_thread` function. Write a Python function `def start_dump_threads_thread(filename_template, timeout, recurrent)` to solve the following problem:
Helper to dump threads after a timeout. :param filename_template: A template filename, such as 'c:/temp/thread_dump_%s.txt', where the %s will be replaced by the time for the dump. :param timeout: The timeout (in seconds) for the dump. :param recurrent: If True we'll keep on doing thread dumps.
Here is the function:
def start_dump_threads_thread(filename_template, timeout, recurrent):
'''
Helper to dump threads after a timeout.
:param filename_template:
A template filename, such as 'c:/temp/thread_dump_%s.txt', where the %s will
be replaced by the time for the dump.
:param timeout:
The timeout (in seconds) for the dump.
:param recurrent:
If True we'll keep on doing thread dumps.
'''
assert filename_template.count('%s') == 1, \
'Expected one %%s to appear in: %s' % (filename_template,)
def _threads_on_timeout():
try:
while True:
time.sleep(timeout)
filename = filename_template % (time.time(),)
try:
os.makedirs(os.path.dirname(filename))
except Exception:
pass
with open(filename, 'w') as stream:
dump_threads(stream)
if not recurrent:
return
except Exception:
pydev_log.exception()
t = threading.Thread(target=_threads_on_timeout)
mark_as_pydevd_daemon_thread(t)
t.start() | Helper to dump threads after a timeout. :param filename_template: A template filename, such as 'c:/temp/thread_dump_%s.txt', where the %s will be replaced by the time for the dump. :param timeout: The timeout (in seconds) for the dump. :param recurrent: If True we'll keep on doing thread dumps. |
177,861 | import sys
if sys.version_info[:2] < (3, 6):
raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.')
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
def usage(doExit=0):
sys.stdout.write('Usage:\n')
sys.stdout.write('pydevd.py --port N [(--client hostname) | --server] --file executable [file_options]\n')
if doExit:
sys.exit(0) | null |
177,862 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
def settrace(
host=None,
stdout_to_server=False,
stderr_to_server=False,
port=5678,
suspend=True,
trace_only_current_thread=False,
overwrite_prev_trace=False,
patch_multiprocessing=False,
stop_at_frame=None,
block_until_connected=True,
wait_for_ready_to_run=True,
dont_trace_start_patterns=(),
dont_trace_end_patterns=(),
access_token=None,
client_access_token=None,
notify_stdin=True,
**kwargs
):
'''Sets the tracing function with the pydev debug function and initializes needed facilities.
:param host: the user may specify another host, if the debug server is not in the same machine (default is the local
host)
:param stdout_to_server: when this is true, the stdout is passed to the debug server
:param stderr_to_server: when this is true, the stderr is passed to the debug server
so that they are printed in its console and not in this process console.
:param port: specifies which port to use for communicating with the server (note that the server must be started
in the same port). @note: currently it's hard-coded at 5678 in the client
:param suspend: whether a breakpoint should be emulated as soon as this function is called.
:param trace_only_current_thread: determines if only the current thread will be traced or all current and future
threads will also have the tracing enabled.
:param overwrite_prev_trace: deprecated
:param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched
processes are debugged.
:param stop_at_frame: if passed it'll stop at the given frame, otherwise it'll stop in the function which
called this method.
:param wait_for_ready_to_run: if True settrace will block until the ready_to_run flag is set to True,
otherwise, it'll set ready_to_run to True and this function won't block.
Note that if wait_for_ready_to_run == False, there are no guarantees that the debugger is synchronized
with what's configured in the client (IDE), the only guarantee is that when leaving this function
the debugger will be already connected.
:param dont_trace_start_patterns: if set, then any path that starts with one fo the patterns in the collection
will not be traced
:param dont_trace_end_patterns: if set, then any path that ends with one fo the patterns in the collection
will not be traced
:param access_token: token to be sent from the client (i.e.: IDE) to the debugger when a connection
is established (verified by the debugger).
:param client_access_token: token to be sent from the debugger to the client (i.e.: IDE) when
a connection is established (verified by the client).
:param notify_stdin:
If True sys.stdin will be patched to notify the client when a message is requested
from the IDE. This is done so that when reading the stdin the client is notified.
Clients may need this to know when something that is being written should be interpreted
as an input to the process or as a command to be evaluated.
Note that parallel-python has issues with this (because it tries to assert that sys.stdin
is of a given type instead of just checking that it has what it needs).
'''
stdout_to_server = stdout_to_server or kwargs.get('stdoutToServer', False) # Backward compatibility
stderr_to_server = stderr_to_server or kwargs.get('stderrToServer', False) # Backward compatibility
# Internal use (may be used to set the setup info directly for subprocesess).
__setup_holder__ = kwargs.get('__setup_holder__')
with _set_trace_lock:
_locked_settrace(
host,
stdout_to_server,
stderr_to_server,
port,
suspend,
trace_only_current_thread,
patch_multiprocessing,
stop_at_frame,
block_until_connected,
wait_for_ready_to_run,
dont_trace_start_patterns,
dont_trace_end_patterns,
access_token,
client_access_token,
__setup_holder__=__setup_holder__,
notify_stdin=notify_stdin,
)
class SetupHolder:
setup = None
The provided code snippet includes necessary dependencies for implementing the `_enable_attach` function. Write a Python function `def _enable_attach( address, dont_trace_start_patterns=(), dont_trace_end_patterns=(), patch_multiprocessing=False, access_token=None, client_access_token=None, )` to solve the following problem:
Starts accepting connections at the given host/port. The debugger will not be initialized nor configured, it'll only start accepting connections (and will have the tracing setup in this thread). Meant to be used with the DAP (Debug Adapter Protocol) with _wait_for_attach(). :param address: (host, port) :type address: tuple(str, int)
Here is the function:
def _enable_attach(
address,
dont_trace_start_patterns=(),
dont_trace_end_patterns=(),
patch_multiprocessing=False,
access_token=None,
client_access_token=None,
):
'''
Starts accepting connections at the given host/port. The debugger will not be initialized nor
configured, it'll only start accepting connections (and will have the tracing setup in this
thread).
Meant to be used with the DAP (Debug Adapter Protocol) with _wait_for_attach().
:param address: (host, port)
:type address: tuple(str, int)
'''
host = address[0]
port = int(address[1])
if SetupHolder.setup is not None:
if port != SetupHolder.setup['port']:
raise AssertionError('Unable to listen in port: %s (already listening in port: %s)' % (port, SetupHolder.setup['port']))
settrace(
host=host,
port=port,
suspend=False,
wait_for_ready_to_run=False,
block_until_connected=False,
dont_trace_start_patterns=dont_trace_start_patterns,
dont_trace_end_patterns=dont_trace_end_patterns,
patch_multiprocessing=patch_multiprocessing,
access_token=access_token,
client_access_token=client_access_token,
)
py_db = get_global_debugger()
py_db.wait_for_server_socket_ready()
return py_db._server_socket_name | Starts accepting connections at the given host/port. The debugger will not be initialized nor configured, it'll only start accepting connections (and will have the tracing setup in this thread). Meant to be used with the DAP (Debug Adapter Protocol) with _wait_for_attach(). :param address: (host, port) :type address: tuple(str, int) |
177,863 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
The provided code snippet includes necessary dependencies for implementing the `_wait_for_attach` function. Write a Python function `def _wait_for_attach(cancel=None)` to solve the following problem:
Meant to be called after _enable_attach() -- the current thread will only unblock after a connection is in place and the DAP (Debug Adapter Protocol) sends the ConfigurationDone request.
Here is the function:
def _wait_for_attach(cancel=None):
'''
Meant to be called after _enable_attach() -- the current thread will only unblock after a
connection is in place and the DAP (Debug Adapter Protocol) sends the ConfigurationDone
request.
'''
py_db = get_global_debugger()
if py_db is None:
raise AssertionError('Debugger still not created. Please use _enable_attach() before using _wait_for_attach().')
py_db.block_until_configuration_done(cancel=cancel) | Meant to be called after _enable_attach() -- the current thread will only unblock after a connection is in place and the DAP (Debug Adapter Protocol) sends the ConfigurationDone request. |
177,864 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
The provided code snippet includes necessary dependencies for implementing the `_is_attached` function. Write a Python function `def _is_attached()` to solve the following problem:
Can be called any time to check if the connection was established and the DAP (Debug Adapter Protocol) has sent the ConfigurationDone request.
Here is the function:
def _is_attached():
'''
Can be called any time to check if the connection was established and the DAP (Debug Adapter Protocol) has sent
the ConfigurationDone request.
'''
py_db = get_global_debugger()
return (py_db is not None) and py_db.is_attached() | Can be called any time to check if the connection was established and the DAP (Debug Adapter Protocol) has sent the ConfigurationDone request. |
177,865 | import sys
if sys.version_info[:2] < (3, 6):
raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.')
import os
try:
# Just empty packages to check if they're in the PYTHONPATH.
import _pydev_bundle
except ImportError:
# On the first import of a pydevd module, add pydevd itself to the PYTHONPATH
# if its dependencies cannot be imported.
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import _pydev_bundle
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT)
pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__))
pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
def settrace(
host=None,
stdout_to_server=False,
stderr_to_server=False,
port=5678,
suspend=True,
trace_only_current_thread=False,
overwrite_prev_trace=False,
patch_multiprocessing=False,
stop_at_frame=None,
block_until_connected=True,
wait_for_ready_to_run=True,
dont_trace_start_patterns=(),
dont_trace_end_patterns=(),
access_token=None,
client_access_token=None,
notify_stdin=True,
**kwargs
):
'''Sets the tracing function with the pydev debug function and initializes needed facilities.
:param host: the user may specify another host, if the debug server is not in the same machine (default is the local
host)
:param stdout_to_server: when this is true, the stdout is passed to the debug server
:param stderr_to_server: when this is true, the stderr is passed to the debug server
so that they are printed in its console and not in this process console.
:param port: specifies which port to use for communicating with the server (note that the server must be started
in the same port). @note: currently it's hard-coded at 5678 in the client
:param suspend: whether a breakpoint should be emulated as soon as this function is called.
:param trace_only_current_thread: determines if only the current thread will be traced or all current and future
threads will also have the tracing enabled.
:param overwrite_prev_trace: deprecated
:param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched
processes are debugged.
:param stop_at_frame: if passed it'll stop at the given frame, otherwise it'll stop in the function which
called this method.
:param wait_for_ready_to_run: if True settrace will block until the ready_to_run flag is set to True,
otherwise, it'll set ready_to_run to True and this function won't block.
Note that if wait_for_ready_to_run == False, there are no guarantees that the debugger is synchronized
with what's configured in the client (IDE), the only guarantee is that when leaving this function
the debugger will be already connected.
:param dont_trace_start_patterns: if set, then any path that starts with one fo the patterns in the collection
will not be traced
:param dont_trace_end_patterns: if set, then any path that ends with one fo the patterns in the collection
will not be traced
:param access_token: token to be sent from the client (i.e.: IDE) to the debugger when a connection
is established (verified by the debugger).
:param client_access_token: token to be sent from the debugger to the client (i.e.: IDE) when
a connection is established (verified by the client).
:param notify_stdin:
If True sys.stdin will be patched to notify the client when a message is requested
from the IDE. This is done so that when reading the stdin the client is notified.
Clients may need this to know when something that is being written should be interpreted
as an input to the process or as a command to be evaluated.
Note that parallel-python has issues with this (because it tries to assert that sys.stdin
is of a given type instead of just checking that it has what it needs).
'''
stdout_to_server = stdout_to_server or kwargs.get('stdoutToServer', False) # Backward compatibility
stderr_to_server = stderr_to_server or kwargs.get('stderrToServer', False) # Backward compatibility
# Internal use (may be used to set the setup info directly for subprocesess).
__setup_holder__ = kwargs.get('__setup_holder__')
with _set_trace_lock:
_locked_settrace(
host,
stdout_to_server,
stderr_to_server,
port,
suspend,
trace_only_current_thread,
patch_multiprocessing,
stop_at_frame,
block_until_connected,
wait_for_ready_to_run,
dont_trace_start_patterns,
dont_trace_end_patterns,
access_token,
client_access_token,
__setup_holder__=__setup_holder__,
notify_stdin=notify_stdin,
)
def undo_patch_thread_modules():
for t in threading_modules_to_patch:
try:
t.start_new_thread = t._original_start_new_thread
except:
pass
try:
t.start_new = t._original_start_new_thread
except:
pass
try:
t._start_new_thread = t._original_start_new_thread
except:
pass
def stoptrace():
pydev_log.debug("pydevd.stoptrace()")
pydevd_tracing.restore_sys_set_trace_func()
sys.settrace(None)
try:
# not available in jython!
threading.settrace(None) # for all future threads
except:
pass
from _pydev_bundle.pydev_monkey import undo_patch_thread_modules
undo_patch_thread_modules()
# Either or both standard streams can be closed at this point,
# in which case flush() will fail.
try:
sys.stdout.flush()
except:
pass
try:
sys.stderr.flush()
except:
pass
py_db = get_global_debugger()
if py_db is not None:
py_db.dispose_and_kill_all_pydevd_threads() | null |
177,866 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
if pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING:
pydev_log.debug('PYDEVD_IPYTHON_CONTEXT: %s', pydevd_constants.PYDEVD_IPYTHON_CONTEXT)
def settrace(
host=None,
stdout_to_server=False,
stderr_to_server=False,
port=5678,
suspend=True,
trace_only_current_thread=False,
overwrite_prev_trace=False,
patch_multiprocessing=False,
stop_at_frame=None,
block_until_connected=True,
wait_for_ready_to_run=True,
dont_trace_start_patterns=(),
dont_trace_end_patterns=(),
access_token=None,
client_access_token=None,
notify_stdin=True,
**kwargs
):
'''Sets the tracing function with the pydev debug function and initializes needed facilities.
:param host: the user may specify another host, if the debug server is not in the same machine (default is the local
host)
:param stdout_to_server: when this is true, the stdout is passed to the debug server
:param stderr_to_server: when this is true, the stderr is passed to the debug server
so that they are printed in its console and not in this process console.
:param port: specifies which port to use for communicating with the server (note that the server must be started
in the same port). @note: currently it's hard-coded at 5678 in the client
:param suspend: whether a breakpoint should be emulated as soon as this function is called.
:param trace_only_current_thread: determines if only the current thread will be traced or all current and future
threads will also have the tracing enabled.
:param overwrite_prev_trace: deprecated
:param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched
processes are debugged.
:param stop_at_frame: if passed it'll stop at the given frame, otherwise it'll stop in the function which
called this method.
:param wait_for_ready_to_run: if True settrace will block until the ready_to_run flag is set to True,
otherwise, it'll set ready_to_run to True and this function won't block.
Note that if wait_for_ready_to_run == False, there are no guarantees that the debugger is synchronized
with what's configured in the client (IDE), the only guarantee is that when leaving this function
the debugger will be already connected.
:param dont_trace_start_patterns: if set, then any path that starts with one fo the patterns in the collection
will not be traced
:param dont_trace_end_patterns: if set, then any path that ends with one fo the patterns in the collection
will not be traced
:param access_token: token to be sent from the client (i.e.: IDE) to the debugger when a connection
is established (verified by the debugger).
:param client_access_token: token to be sent from the debugger to the client (i.e.: IDE) when
a connection is established (verified by the client).
:param notify_stdin:
If True sys.stdin will be patched to notify the client when a message is requested
from the IDE. This is done so that when reading the stdin the client is notified.
Clients may need this to know when something that is being written should be interpreted
as an input to the process or as a command to be evaluated.
Note that parallel-python has issues with this (because it tries to assert that sys.stdin
is of a given type instead of just checking that it has what it needs).
'''
stdout_to_server = stdout_to_server or kwargs.get('stdoutToServer', False) # Backward compatibility
stderr_to_server = stderr_to_server or kwargs.get('stderrToServer', False) # Backward compatibility
# Internal use (may be used to set the setup info directly for subprocesess).
__setup_holder__ = kwargs.get('__setup_holder__')
with _set_trace_lock:
_locked_settrace(
host,
stdout_to_server,
stderr_to_server,
port,
suspend,
trace_only_current_thread,
patch_multiprocessing,
stop_at_frame,
block_until_connected,
wait_for_ready_to_run,
dont_trace_start_patterns,
dont_trace_end_patterns,
access_token,
client_access_token,
__setup_holder__=__setup_holder__,
notify_stdin=notify_stdin,
)
def dispatch():
setup = SetupHolder.setup
host = setup['client']
port = setup['port']
if DISPATCH_APPROACH == DISPATCH_APPROACH_EXISTING_CONNECTION:
dispatcher = Dispatcher()
try:
dispatcher.connect(host, port)
port = dispatcher.port
finally:
dispatcher.close()
return host, port
class SetupHolder:
setup = None
class GlobalDebuggerHolder:
'''
Holder for the global debugger.
'''
global_dbg = None # Note: don't rename (the name is used in our attach to process)
def custom_frames_container_init(): # Note: no staticmethod on jython 2.1 (so, use free-function)
CustomFramesContainer.custom_frames_lock = ForkSafeLock()
# custom_frames can only be accessed if properly locked with custom_frames_lock!
# Key is a string identifying the frame (as well as the thread it belongs to).
# Value is a CustomFrame.
#
CustomFramesContainer.custom_frames = {}
# Only to be used in this module
CustomFramesContainer._next_frame_id = 0
# This is the event we must set to release an internal process events. It's later set by the actual debugger
# when we do create the debugger.
CustomFramesContainer._py_db_command_thread_event = Null()
custom_frames_container_init()
class PyDevdAPI(object):
class VariablePresentation(object):
def __init__(self, special='group', function='group', class_='group', protected='inline'):
self._presentation = {
DAPGrouper.SCOPE_SPECIAL_VARS: special,
DAPGrouper.SCOPE_FUNCTION_VARS: function,
DAPGrouper.SCOPE_CLASS_VARS: class_,
DAPGrouper.SCOPE_PROTECTED_VARS: protected,
}
def get_presentation(self, scope):
return self._presentation[scope]
def run(self, py_db):
py_db.ready_to_run = True
def notify_initialize(self, py_db):
py_db.on_initialize()
def notify_configuration_done(self, py_db):
py_db.on_configuration_done()
def notify_disconnect(self, py_db):
py_db.on_disconnect()
def set_protocol(self, py_db, seq, protocol):
set_protocol(protocol.strip())
if get_protocol() in (HTTP_JSON_PROTOCOL, JSON_PROTOCOL):
cmd_factory_class = NetCommandFactoryJson
else:
cmd_factory_class = NetCommandFactory
if not isinstance(py_db.cmd_factory, cmd_factory_class):
py_db.cmd_factory = cmd_factory_class()
return py_db.cmd_factory.make_protocol_set_message(seq)
def set_ide_os_and_breakpoints_by(self, py_db, seq, ide_os, breakpoints_by):
'''
:param ide_os: 'WINDOWS' or 'UNIX'
:param breakpoints_by: 'ID' or 'LINE'
'''
if breakpoints_by == 'ID':
py_db._set_breakpoints_with_id = True
else:
py_db._set_breakpoints_with_id = False
self.set_ide_os(ide_os)
return py_db.cmd_factory.make_version_message(seq)
def set_ide_os(self, ide_os):
'''
:param ide_os: 'WINDOWS' or 'UNIX'
'''
pydevd_file_utils.set_ide_os(ide_os)
def set_gui_event_loop(self, py_db, gui_event_loop):
py_db._gui_event_loop = gui_event_loop
def send_error_message(self, py_db, msg):
cmd = py_db.cmd_factory.make_warning_message('pydevd: %s\n' % (msg,))
py_db.writer.add_command(cmd)
def set_show_return_values(self, py_db, show_return_values):
if show_return_values:
py_db.show_return_values = True
else:
if py_db.show_return_values:
# We should remove saved return values
py_db.remove_return_values_flag = True
py_db.show_return_values = False
pydev_log.debug("Show return values: %s", py_db.show_return_values)
def list_threads(self, py_db, seq):
# Response is the command with the list of threads to be added to the writer thread.
return py_db.cmd_factory.make_list_threads_message(py_db, seq)
def request_suspend_thread(self, py_db, thread_id='*'):
# Yes, thread suspend is done at this point, not through an internal command.
threads = []
suspend_all = thread_id.strip() == '*'
if suspend_all:
threads = pydevd_utils.get_non_pydevd_threads()
elif thread_id.startswith('__frame__:'):
sys.stderr.write("Can't suspend tasklet: %s\n" % (thread_id,))
else:
threads = [pydevd_find_thread_by_id(thread_id)]
for t in threads:
if t is None:
continue
py_db.set_suspend(
t,
CMD_THREAD_SUSPEND,
suspend_other_threads=suspend_all,
is_pause=True,
)
# Break here (even if it's suspend all) as py_db.set_suspend will
# take care of suspending other threads.
break
def set_enable_thread_notifications(self, py_db, enable):
'''
When disabled, no thread notifications (for creation/removal) will be
issued until it's re-enabled.
Note that when it's re-enabled, a creation notification will be sent for
all existing threads even if it was previously sent (this is meant to
be used on disconnect/reconnect).
'''
py_db.set_enable_thread_notifications(enable)
def request_disconnect(self, py_db, resume_threads):
self.set_enable_thread_notifications(py_db, False)
self.remove_all_breakpoints(py_db, '*')
self.remove_all_exception_breakpoints(py_db)
self.notify_disconnect(py_db)
if resume_threads:
self.request_resume_thread(thread_id='*')
def request_resume_thread(self, thread_id):
resume_threads(thread_id)
def request_completions(self, py_db, seq, thread_id, frame_id, act_tok, line=-1, column=-1):
py_db.post_method_as_internal_command(
thread_id, internal_get_completions, seq, thread_id, frame_id, act_tok, line=line, column=column)
def request_stack(self, py_db, seq, thread_id, fmt=None, timeout=.5, start_frame=0, levels=0):
# If it's already suspended, get it right away.
internal_get_thread_stack = InternalGetThreadStack(
seq, thread_id, py_db, set_additional_thread_info, fmt=fmt, timeout=timeout, start_frame=start_frame, levels=levels)
if internal_get_thread_stack.can_be_executed_by(get_current_thread_id(threading.current_thread())):
internal_get_thread_stack.do_it(py_db)
else:
py_db.post_internal_command(internal_get_thread_stack, '*')
def request_exception_info_json(self, py_db, request, thread_id, thread, max_frames):
py_db.post_method_as_internal_command(
thread_id,
internal_get_exception_details_json,
request,
thread_id,
thread,
max_frames,
set_additional_thread_info=set_additional_thread_info,
iter_visible_frames_info=py_db.cmd_factory._iter_visible_frames_info,
)
def request_step(self, py_db, thread_id, step_cmd_id):
t = pydevd_find_thread_by_id(thread_id)
if t:
py_db.post_method_as_internal_command(
thread_id,
internal_step_in_thread,
thread_id,
step_cmd_id,
set_additional_thread_info=set_additional_thread_info,
)
elif thread_id.startswith('__frame__:'):
sys.stderr.write("Can't make tasklet step command: %s\n" % (thread_id,))
def request_smart_step_into(self, py_db, seq, thread_id, offset, child_offset):
t = pydevd_find_thread_by_id(thread_id)
if t:
py_db.post_method_as_internal_command(
thread_id, internal_smart_step_into, thread_id, offset, child_offset, set_additional_thread_info=set_additional_thread_info)
elif thread_id.startswith('__frame__:'):
sys.stderr.write("Can't set next statement in tasklet: %s\n" % (thread_id,))
def request_smart_step_into_by_func_name(self, py_db, seq, thread_id, line, func_name):
# Same thing as set next, just with a different cmd id.
self.request_set_next(py_db, seq, thread_id, CMD_SMART_STEP_INTO, None, line, func_name)
def request_set_next(self, py_db, seq, thread_id, set_next_cmd_id, original_filename, line, func_name):
'''
set_next_cmd_id may actually be one of:
CMD_RUN_TO_LINE
CMD_SET_NEXT_STATEMENT
CMD_SMART_STEP_INTO -- note: request_smart_step_into is preferred if it's possible
to work with bytecode offset.
:param Optional[str] original_filename:
If available, the filename may be source translated, otherwise no translation will take
place (the set next just needs the line afterwards as it executes locally, but for
the Jupyter integration, the source mapping may change the actual lines and not only
the filename).
'''
t = pydevd_find_thread_by_id(thread_id)
if t:
if original_filename is not None:
translated_filename = self.filename_to_server(original_filename) # Apply user path mapping.
pydev_log.debug('Set next (after path translation) in: %s line: %s', translated_filename, line)
func_name = self.to_str(func_name)
assert translated_filename.__class__ == str # i.e.: bytes on py2 and str on py3
assert func_name.__class__ == str # i.e.: bytes on py2 and str on py3
# Apply source mapping (i.e.: ipython).
_source_mapped_filename, new_line, multi_mapping_applied = py_db.source_mapping.map_to_server(
translated_filename, line)
if multi_mapping_applied:
pydev_log.debug('Set next (after source mapping) in: %s line: %s', translated_filename, line)
line = new_line
int_cmd = InternalSetNextStatementThread(thread_id, set_next_cmd_id, line, func_name, seq=seq)
py_db.post_internal_command(int_cmd, thread_id)
elif thread_id.startswith('__frame__:'):
sys.stderr.write("Can't set next statement in tasklet: %s\n" % (thread_id,))
def request_reload_code(self, py_db, seq, module_name, filename):
'''
:param seq: if -1 no message will be sent back when the reload is done.
Note: either module_name or filename may be None (but not both at the same time).
'''
thread_id = '*' # Any thread
# Note: not going for the main thread because in this case it'd only do the load
# when we stopped on a breakpoint.
py_db.post_method_as_internal_command(
thread_id, internal_reload_code, seq, module_name, filename)
def request_change_variable(self, py_db, seq, thread_id, frame_id, scope, attr, value):
'''
:param scope: 'FRAME' or 'GLOBAL'
'''
py_db.post_method_as_internal_command(
thread_id, internal_change_variable, seq, thread_id, frame_id, scope, attr, value)
def request_get_variable(self, py_db, seq, thread_id, frame_id, scope, attrs):
'''
:param scope: 'FRAME' or 'GLOBAL'
'''
int_cmd = InternalGetVariable(seq, thread_id, frame_id, scope, attrs)
py_db.post_internal_command(int_cmd, thread_id)
def request_get_array(self, py_db, seq, roffset, coffset, rows, cols, fmt, thread_id, frame_id, scope, attrs):
int_cmd = InternalGetArray(seq, roffset, coffset, rows, cols, fmt, thread_id, frame_id, scope, attrs)
py_db.post_internal_command(int_cmd, thread_id)
def request_load_full_value(self, py_db, seq, thread_id, frame_id, vars):
int_cmd = InternalLoadFullValue(seq, thread_id, frame_id, vars)
py_db.post_internal_command(int_cmd, thread_id)
def request_get_description(self, py_db, seq, thread_id, frame_id, expression):
py_db.post_method_as_internal_command(
thread_id, internal_get_description, seq, thread_id, frame_id, expression)
def request_get_frame(self, py_db, seq, thread_id, frame_id):
py_db.post_method_as_internal_command(
thread_id, internal_get_frame, seq, thread_id, frame_id)
def to_str(self, s):
'''
-- in py3 raises an error if it's not str already.
'''
if s.__class__ != str:
raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (s, s.__class__))
return s
def filename_to_str(self, filename):
'''
-- in py3 raises an error if it's not str already.
'''
if filename.__class__ != str:
raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (filename, filename.__class__))
return filename
def filename_to_server(self, filename):
filename = self.filename_to_str(filename)
filename = pydevd_file_utils.map_file_to_server(filename)
return filename
class _DummyFrame(object):
'''
Dummy frame to be used with PyDB.apply_files_filter (as we don't really have the
related frame as breakpoints are added before execution).
'''
class _DummyCode(object):
def __init__(self, filename):
self.co_firstlineno = 1
self.co_filename = filename
self.co_name = 'invalid func name '
def __init__(self, filename):
self.f_code = self._DummyCode(filename)
self.f_globals = {}
ADD_BREAKPOINT_NO_ERROR = 0
ADD_BREAKPOINT_FILE_NOT_FOUND = 1
ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS = 2
# This means that the breakpoint couldn't be fully validated (more runtime
# information may be needed).
ADD_BREAKPOINT_LAZY_VALIDATION = 3
ADD_BREAKPOINT_INVALID_LINE = 4
class _AddBreakpointResult(object):
# :see: ADD_BREAKPOINT_NO_ERROR = 0
# :see: ADD_BREAKPOINT_FILE_NOT_FOUND = 1
# :see: ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS = 2
# :see: ADD_BREAKPOINT_LAZY_VALIDATION = 3
# :see: ADD_BREAKPOINT_INVALID_LINE = 4
__slots__ = ['error_code', 'breakpoint_id', 'translated_filename', 'translated_line', 'original_line']
def __init__(self, breakpoint_id, translated_filename, translated_line, original_line):
self.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR
self.breakpoint_id = breakpoint_id
self.translated_filename = translated_filename
self.translated_line = translated_line
self.original_line = original_line
def add_breakpoint(
self, py_db, original_filename, breakpoint_type, breakpoint_id, line, condition, func_name,
expression, suspend_policy, hit_condition, is_logpoint, adjust_line=False, on_changed_breakpoint_state=None):
'''
:param str original_filename:
Note: must be sent as it was received in the protocol. It may be translated in this
function and its final value will be available in the returned _AddBreakpointResult.
:param str breakpoint_type:
One of: 'python-line', 'django-line', 'jinja2-line'.
:param int breakpoint_id:
:param int line:
Note: it's possible that a new line was actually used. If that's the case its
final value will be available in the returned _AddBreakpointResult.
:param condition:
Either None or the condition to activate the breakpoint.
:param str func_name:
If "None" (str), may hit in any context.
Empty string will hit only top level.
Any other value must match the scope of the method to be matched.
:param str expression:
None or the expression to be evaluated.
:param suspend_policy:
Either "NONE" (to suspend only the current thread when the breakpoint is hit) or
"ALL" (to suspend all threads when a breakpoint is hit).
:param str hit_condition:
An expression where `@HIT@` will be replaced by the number of hits.
i.e.: `@HIT@ == x` or `@HIT@ >= x`
:param bool is_logpoint:
If True and an expression is passed, pydevd will create an io message command with the
result of the evaluation.
:param bool adjust_line:
If True, the breakpoint line should be adjusted if the current line doesn't really
match an executable line (if possible).
:param callable on_changed_breakpoint_state:
This is called when something changed internally on the breakpoint after it was initially
added (for instance, template file_to_line_to_breakpoints could be signaled as invalid initially and later
when the related template is loaded, if the line is valid it could be marked as valid).
The signature for the callback should be:
on_changed_breakpoint_state(breakpoint_id: int, add_breakpoint_result: _AddBreakpointResult)
Note that the add_breakpoint_result should not be modified by the callback (the
implementation may internally reuse the same instance multiple times).
:return _AddBreakpointResult:
'''
assert original_filename.__class__ == str, 'Expected str, found: %s' % (original_filename.__class__,) # i.e.: bytes on py2 and str on py3
original_filename_normalized = pydevd_file_utils.normcase_from_client(original_filename)
pydev_log.debug('Request for breakpoint in: %s line: %s', original_filename, line)
original_line = line
# Parameters to reapply breakpoint.
api_add_breakpoint_params = (original_filename, breakpoint_type, breakpoint_id, line, condition, func_name,
expression, suspend_policy, hit_condition, is_logpoint)
translated_filename = self.filename_to_server(original_filename) # Apply user path mapping.
pydev_log.debug('Breakpoint (after path translation) in: %s line: %s', translated_filename, line)
func_name = self.to_str(func_name)
assert translated_filename.__class__ == str # i.e.: bytes on py2 and str on py3
assert func_name.__class__ == str # i.e.: bytes on py2 and str on py3
# Apply source mapping (i.e.: ipython).
source_mapped_filename, new_line, multi_mapping_applied = py_db.source_mapping.map_to_server(
translated_filename, line)
if multi_mapping_applied:
pydev_log.debug('Breakpoint (after source mapping) in: %s line: %s', source_mapped_filename, new_line)
# Note that source mapping is internal and does not change the resulting filename nor line
# (we want the outside world to see the line in the original file and not in the ipython
# cell, otherwise the editor wouldn't be correct as the returned line is the line to
# which the breakpoint will be moved in the editor).
result = self._AddBreakpointResult(breakpoint_id, original_filename, line, original_line)
# If a multi-mapping was applied, consider it the canonical / source mapped version (translated to ipython cell).
translated_absolute_filename = source_mapped_filename
canonical_normalized_filename = pydevd_file_utils.normcase(source_mapped_filename)
line = new_line
else:
translated_absolute_filename = pydevd_file_utils.absolute_path(translated_filename)
canonical_normalized_filename = pydevd_file_utils.canonical_normalized_path(translated_filename)
if adjust_line and not translated_absolute_filename.startswith('<'):
# Validate file_to_line_to_breakpoints and adjust their positions.
try:
lines = sorted(_get_code_lines(translated_absolute_filename))
except Exception:
pass
else:
if line not in lines:
# Adjust to the first preceding valid line.
idx = bisect.bisect_left(lines, line)
if idx > 0:
line = lines[idx - 1]
result = self._AddBreakpointResult(breakpoint_id, original_filename, line, original_line)
py_db.api_received_breakpoints[(original_filename_normalized, breakpoint_id)] = (canonical_normalized_filename, api_add_breakpoint_params)
if not translated_absolute_filename.startswith('<'):
# Note: if a mapping pointed to a file starting with '<', don't validate.
if not pydevd_file_utils.exists(translated_absolute_filename):
result.error_code = self.ADD_BREAKPOINT_FILE_NOT_FOUND
return result
if (
py_db.is_files_filter_enabled and
not py_db.get_require_module_for_filters() and
py_db.apply_files_filter(self._DummyFrame(translated_absolute_filename), translated_absolute_filename, False)
):
# Note that if `get_require_module_for_filters()` returns False, we don't do this check.
# This is because we don't have the module name given a file at this point (in
# runtime it's gotten from the frame.f_globals).
# An option could be calculate it based on the filename and current sys.path,
# but on some occasions that may be wrong (for instance with `__main__` or if
# the user dynamically changes the PYTHONPATH).
# Note: depending on the use-case, filters may be changed, so, keep on going and add the
# breakpoint even with the error code.
result.error_code = self.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS
if breakpoint_type == 'python-line':
added_breakpoint = LineBreakpoint(
breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition=hit_condition, is_logpoint=is_logpoint)
file_to_line_to_breakpoints = py_db.breakpoints
file_to_id_to_breakpoint = py_db.file_to_id_to_line_breakpoint
supported_type = True
else:
add_plugin_breakpoint_result = None
plugin = py_db.get_plugin_lazy_init()
if plugin is not None:
add_plugin_breakpoint_result = plugin.add_breakpoint(
'add_line_breakpoint', py_db, breakpoint_type, canonical_normalized_filename,
breakpoint_id, line, condition, expression, func_name, hit_condition=hit_condition, is_logpoint=is_logpoint,
add_breakpoint_result=result, on_changed_breakpoint_state=on_changed_breakpoint_state)
if add_plugin_breakpoint_result is not None:
supported_type = True
added_breakpoint, file_to_line_to_breakpoints = add_plugin_breakpoint_result
file_to_id_to_breakpoint = py_db.file_to_id_to_plugin_breakpoint
else:
supported_type = False
if not supported_type:
raise NameError(breakpoint_type)
pydev_log.debug('Added breakpoint:%s - line:%s - func_name:%s\n', canonical_normalized_filename, line, func_name)
if canonical_normalized_filename in file_to_id_to_breakpoint:
id_to_pybreakpoint = file_to_id_to_breakpoint[canonical_normalized_filename]
else:
id_to_pybreakpoint = file_to_id_to_breakpoint[canonical_normalized_filename] = {}
id_to_pybreakpoint[breakpoint_id] = added_breakpoint
py_db.consolidate_breakpoints(canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints)
if py_db.plugin is not None:
py_db.has_plugin_line_breaks = py_db.plugin.has_line_breaks()
py_db.plugin.after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints)
py_db.on_breakpoints_changed()
return result
def reapply_breakpoints(self, py_db):
'''
Reapplies all the received breakpoints as they were received by the API (so, new
translations are applied).
'''
pydev_log.debug('Reapplying breakpoints.')
values = list(py_db.api_received_breakpoints.values()) # Create a copy with items to reapply.
self.remove_all_breakpoints(py_db, '*')
for val in values:
_new_filename, api_add_breakpoint_params = val
self.add_breakpoint(py_db, *api_add_breakpoint_params)
def remove_all_breakpoints(self, py_db, received_filename):
'''
Removes all the breakpoints from a given file or from all files if received_filename == '*'.
:param str received_filename:
Note: must be sent as it was received in the protocol. It may be translated in this
function.
'''
assert received_filename.__class__ == str # i.e.: bytes on py2 and str on py3
changed = False
lst = [
py_db.file_to_id_to_line_breakpoint,
py_db.file_to_id_to_plugin_breakpoint,
py_db.breakpoints
]
if hasattr(py_db, 'django_breakpoints'):
lst.append(py_db.django_breakpoints)
if hasattr(py_db, 'jinja2_breakpoints'):
lst.append(py_db.jinja2_breakpoints)
if received_filename == '*':
py_db.api_received_breakpoints.clear()
for file_to_id_to_breakpoint in lst:
if file_to_id_to_breakpoint:
file_to_id_to_breakpoint.clear()
changed = True
else:
received_filename_normalized = pydevd_file_utils.normcase_from_client(received_filename)
items = list(py_db.api_received_breakpoints.items()) # Create a copy to remove items.
translated_filenames = []
for key, val in items:
original_filename_normalized, _breakpoint_id = key
if original_filename_normalized == received_filename_normalized:
canonical_normalized_filename, _api_add_breakpoint_params = val
# Note: there can be actually 1:N mappings due to source mapping (i.e.: ipython).
translated_filenames.append(canonical_normalized_filename)
del py_db.api_received_breakpoints[key]
for canonical_normalized_filename in translated_filenames:
for file_to_id_to_breakpoint in lst:
if canonical_normalized_filename in file_to_id_to_breakpoint:
file_to_id_to_breakpoint.pop(canonical_normalized_filename, None)
changed = True
if changed:
py_db.on_breakpoints_changed(removed=True)
def remove_breakpoint(self, py_db, received_filename, breakpoint_type, breakpoint_id):
'''
:param str received_filename:
Note: must be sent as it was received in the protocol. It may be translated in this
function.
:param str breakpoint_type:
One of: 'python-line', 'django-line', 'jinja2-line'.
:param int breakpoint_id:
'''
received_filename_normalized = pydevd_file_utils.normcase_from_client(received_filename)
for key, val in list(py_db.api_received_breakpoints.items()):
original_filename_normalized, existing_breakpoint_id = key
_new_filename, _api_add_breakpoint_params = val
if received_filename_normalized == original_filename_normalized and existing_breakpoint_id == breakpoint_id:
del py_db.api_received_breakpoints[key]
break
else:
pydev_log.info(
'Did not find breakpoint to remove: %s (breakpoint id: %s)', received_filename, breakpoint_id)
file_to_id_to_breakpoint = None
received_filename = self.filename_to_server(received_filename)
canonical_normalized_filename = pydevd_file_utils.canonical_normalized_path(received_filename)
if breakpoint_type == 'python-line':
file_to_line_to_breakpoints = py_db.breakpoints
file_to_id_to_breakpoint = py_db.file_to_id_to_line_breakpoint
elif py_db.plugin is not None:
result = py_db.plugin.get_breakpoints(py_db, breakpoint_type)
if result is not None:
file_to_id_to_breakpoint = py_db.file_to_id_to_plugin_breakpoint
file_to_line_to_breakpoints = result
if file_to_id_to_breakpoint is None:
pydev_log.critical('Error removing breakpoint. Cannot handle breakpoint of type %s', breakpoint_type)
else:
try:
id_to_pybreakpoint = file_to_id_to_breakpoint.get(canonical_normalized_filename, {})
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
existing = id_to_pybreakpoint[breakpoint_id]
pydev_log.info('Removed breakpoint:%s - line:%s - func_name:%s (id: %s)\n' % (
canonical_normalized_filename, existing.line, existing.func_name, breakpoint_id))
del id_to_pybreakpoint[breakpoint_id]
py_db.consolidate_breakpoints(canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints)
if py_db.plugin is not None:
py_db.has_plugin_line_breaks = py_db.plugin.has_line_breaks()
py_db.plugin.after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints)
except KeyError:
pydev_log.info("Error removing breakpoint: Breakpoint id not found: %s id: %s. Available ids: %s\n",
canonical_normalized_filename, breakpoint_id, list(id_to_pybreakpoint))
py_db.on_breakpoints_changed(removed=True)
def set_function_breakpoints(self, py_db, function_breakpoints):
function_breakpoint_name_to_breakpoint = {}
for function_breakpoint in function_breakpoints:
function_breakpoint_name_to_breakpoint[function_breakpoint.func_name] = function_breakpoint
py_db.function_breakpoint_name_to_breakpoint = function_breakpoint_name_to_breakpoint
py_db.on_breakpoints_changed()
def request_exec_or_evaluate(
self, py_db, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result):
py_db.post_method_as_internal_command(
thread_id, internal_evaluate_expression,
seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result)
def request_exec_or_evaluate_json(
self, py_db, request, thread_id):
py_db.post_method_as_internal_command(
thread_id, internal_evaluate_expression_json, request, thread_id)
def request_set_expression_json(self, py_db, request, thread_id):
py_db.post_method_as_internal_command(
thread_id, internal_set_expression_json, request, thread_id)
def request_console_exec(self, py_db, seq, thread_id, frame_id, expression):
int_cmd = InternalConsoleExec(seq, thread_id, frame_id, expression)
py_db.post_internal_command(int_cmd, thread_id)
def request_load_source(self, py_db, seq, filename):
'''
:param str filename:
Note: must be sent as it was received in the protocol. It may be translated in this
function.
'''
try:
filename = self.filename_to_server(filename)
assert filename.__class__ == str # i.e.: bytes on py2 and str on py3
with tokenize.open(filename) as stream:
source = stream.read()
cmd = py_db.cmd_factory.make_load_source_message(seq, source)
except:
cmd = py_db.cmd_factory.make_error_message(seq, get_exception_traceback_str())
py_db.writer.add_command(cmd)
def get_decompiled_source_from_frame_id(self, py_db, frame_id):
'''
:param py_db:
:param frame_id:
:throws Exception:
If unable to get the frame in the currently paused frames or if some error happened
when decompiling.
'''
variable = py_db.suspended_frames_manager.get_variable(int(frame_id))
frame = variable.value
# Check if it's in the linecache first.
lines = (linecache.getline(frame.f_code.co_filename, i) for i in itertools.count(1))
lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is ''
source = ''.join(lines)
if not source:
source = code_to_bytecode_representation(frame.f_code)
return source
def request_load_source_from_frame_id(self, py_db, seq, frame_id):
try:
source = self.get_decompiled_source_from_frame_id(py_db, frame_id)
cmd = py_db.cmd_factory.make_load_source_from_frame_id_message(seq, source)
except:
cmd = py_db.cmd_factory.make_error_message(seq, get_exception_traceback_str())
py_db.writer.add_command(cmd)
def add_python_exception_breakpoint(
self,
py_db,
exception,
condition,
expression,
notify_on_handled_exceptions,
notify_on_unhandled_exceptions,
notify_on_user_unhandled_exceptions,
notify_on_first_raise_only,
ignore_libraries,
):
exception_breakpoint = py_db.add_break_on_exception(
exception,
condition=condition,
expression=expression,
notify_on_handled_exceptions=notify_on_handled_exceptions,
notify_on_unhandled_exceptions=notify_on_unhandled_exceptions,
notify_on_user_unhandled_exceptions=notify_on_user_unhandled_exceptions,
notify_on_first_raise_only=notify_on_first_raise_only,
ignore_libraries=ignore_libraries,
)
if exception_breakpoint is not None:
py_db.on_breakpoints_changed()
def add_plugins_exception_breakpoint(self, py_db, breakpoint_type, exception):
supported_type = False
plugin = py_db.get_plugin_lazy_init()
if plugin is not None:
supported_type = plugin.add_breakpoint('add_exception_breakpoint', py_db, breakpoint_type, exception)
if supported_type:
py_db.has_plugin_exception_breaks = py_db.plugin.has_exception_breaks()
py_db.on_breakpoints_changed()
else:
raise NameError(breakpoint_type)
def remove_python_exception_breakpoint(self, py_db, exception):
try:
cp = py_db.break_on_uncaught_exceptions.copy()
cp.pop(exception, None)
py_db.break_on_uncaught_exceptions = cp
cp = py_db.break_on_caught_exceptions.copy()
cp.pop(exception, None)
py_db.break_on_caught_exceptions = cp
cp = py_db.break_on_user_uncaught_exceptions.copy()
cp.pop(exception, None)
py_db.break_on_user_uncaught_exceptions = cp
except:
pydev_log.exception("Error while removing exception %s", sys.exc_info()[0])
py_db.on_breakpoints_changed(removed=True)
def remove_plugins_exception_breakpoint(self, py_db, exception_type, exception):
# I.e.: no need to initialize lazy (if we didn't have it in the first place, we can't remove
# anything from it anyways).
plugin = py_db.plugin
if plugin is None:
return
supported_type = plugin.remove_exception_breakpoint(py_db, exception_type, exception)
if supported_type:
py_db.has_plugin_exception_breaks = py_db.plugin.has_exception_breaks()
else:
pydev_log.info('No exception of type: %s was previously registered.', exception_type)
py_db.on_breakpoints_changed(removed=True)
def remove_all_exception_breakpoints(self, py_db):
py_db.break_on_uncaught_exceptions = {}
py_db.break_on_caught_exceptions = {}
py_db.break_on_user_uncaught_exceptions = {}
plugin = py_db.plugin
if plugin is not None:
plugin.remove_all_exception_breakpoints(py_db)
py_db.on_breakpoints_changed(removed=True)
def set_project_roots(self, py_db, project_roots):
'''
:param str project_roots:
'''
py_db.set_project_roots(project_roots)
def set_stepping_resumes_all_threads(self, py_db, stepping_resumes_all_threads):
py_db.stepping_resumes_all_threads = stepping_resumes_all_threads
# Add it to the namespace so that it's available as PyDevdAPI.ExcludeFilter
from _pydevd_bundle.pydevd_filtering import ExcludeFilter # noqa
def set_exclude_filters(self, py_db, exclude_filters):
'''
:param list(PyDevdAPI.ExcludeFilter) exclude_filters:
'''
py_db.set_exclude_filters(exclude_filters)
def set_use_libraries_filter(self, py_db, use_libraries_filter):
py_db.set_use_libraries_filter(use_libraries_filter)
def request_get_variable_json(self, py_db, request, thread_id):
'''
:param VariablesRequest request:
'''
py_db.post_method_as_internal_command(
thread_id, internal_get_variable_json, request)
def request_change_variable_json(self, py_db, request, thread_id):
'''
:param SetVariableRequest request:
'''
py_db.post_method_as_internal_command(
thread_id, internal_change_variable_json, request)
def set_dont_trace_start_end_patterns(self, py_db, start_patterns, end_patterns):
# Note: start/end patterns normalized internally.
start_patterns = tuple(pydevd_file_utils.normcase(x) for x in start_patterns)
end_patterns = tuple(pydevd_file_utils.normcase(x) for x in end_patterns)
# After it's set the first time, we can still change it, but we need to reset the
# related caches.
reset_caches = False
dont_trace_start_end_patterns_previously_set = \
py_db.dont_trace_external_files.__name__ == 'custom_dont_trace_external_files'
if not dont_trace_start_end_patterns_previously_set and not start_patterns and not end_patterns:
# If it wasn't set previously and start and end patterns are empty we don't need to do anything.
return
if not py_db.is_cache_file_type_empty():
# i.e.: custom function set in set_dont_trace_start_end_patterns.
if dont_trace_start_end_patterns_previously_set:
reset_caches = py_db.dont_trace_external_files.start_patterns != start_patterns or \
py_db.dont_trace_external_files.end_patterns != end_patterns
else:
reset_caches = True
def custom_dont_trace_external_files(abs_path):
normalized_abs_path = pydevd_file_utils.normcase(abs_path)
return normalized_abs_path.startswith(start_patterns) or normalized_abs_path.endswith(end_patterns)
custom_dont_trace_external_files.start_patterns = start_patterns
custom_dont_trace_external_files.end_patterns = end_patterns
py_db.dont_trace_external_files = custom_dont_trace_external_files
if reset_caches:
py_db.clear_dont_trace_start_end_patterns_caches()
def stop_on_entry(self):
main_thread = pydevd_utils.get_main_thread()
if main_thread is None:
pydev_log.critical('Could not find main thread while setting Stop on Entry.')
else:
info = set_additional_thread_info(main_thread)
info.pydev_original_step_cmd = CMD_STOP_ON_START
info.pydev_step_cmd = CMD_STEP_INTO_MY_CODE
def set_ignore_system_exit_codes(self, py_db, ignore_system_exit_codes):
py_db.set_ignore_system_exit_codes(ignore_system_exit_codes)
SourceMappingEntry = pydevd_source_mapping.SourceMappingEntry
def set_source_mapping(self, py_db, source_filename, mapping):
'''
:param str source_filename:
The filename for the source mapping (bytes on py2 and str on py3).
This filename will be made absolute in this function.
:param list(SourceMappingEntry) mapping:
A list with the source mapping entries to be applied to the given filename.
:return str:
An error message if it was not possible to set the mapping or an empty string if
everything is ok.
'''
source_filename = self.filename_to_server(source_filename)
absolute_source_filename = pydevd_file_utils.absolute_path(source_filename)
for map_entry in mapping:
map_entry.source_filename = absolute_source_filename
error_msg = py_db.source_mapping.set_source_mapping(absolute_source_filename, mapping)
if error_msg:
return error_msg
self.reapply_breakpoints(py_db)
return ''
def set_variable_presentation(self, py_db, variable_presentation):
assert isinstance(variable_presentation, self.VariablePresentation)
py_db.variable_presentation = variable_presentation
def get_ppid(self):
'''
Provides the parent pid (even for older versions of Python on Windows).
'''
ppid = None
try:
ppid = os.getppid()
except AttributeError:
pass
if ppid is None and IS_WINDOWS:
ppid = self._get_windows_ppid()
return ppid
def _get_windows_ppid(self):
this_pid = os.getpid()
for ppid, pid in _list_ppid_and_pid():
if pid == this_pid:
return ppid
return None
def _terminate_child_processes_windows(self, dont_terminate_child_pids):
this_pid = os.getpid()
for _ in range(50): # Try this at most 50 times before giving up.
# Note: we can't kill the process itself with taskkill, so, we
# list immediate children, kill that tree and then exit this process.
children_pids = []
for ppid, pid in _list_ppid_and_pid():
if ppid == this_pid:
if pid not in dont_terminate_child_pids:
children_pids.append(pid)
if not children_pids:
break
else:
for pid in children_pids:
self._call(
['taskkill', '/F', '/PID', str(pid), '/T'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
del children_pids[:]
def _terminate_child_processes_linux_and_mac(self, dont_terminate_child_pids):
this_pid = os.getpid()
def list_children_and_stop_forking(initial_pid, stop=True):
children_pids = []
if stop:
# Ask to stop forking (shouldn't be called for this process, only subprocesses).
self._call(
['kill', '-STOP', str(initial_pid)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
list_popen = self._popen(
['pgrep', '-P', str(initial_pid)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if list_popen is not None:
stdout, _ = list_popen.communicate()
for line in stdout.splitlines():
line = line.decode('ascii').strip()
if line:
pid = str(line)
if pid in dont_terminate_child_pids:
continue
children_pids.append(pid)
# Recursively get children.
children_pids.extend(list_children_and_stop_forking(pid))
return children_pids
previously_found = set()
for _ in range(50): # Try this at most 50 times before giving up.
children_pids = list_children_and_stop_forking(this_pid, stop=False)
found_new = False
for pid in children_pids:
if pid not in previously_found:
found_new = True
previously_found.add(pid)
self._call(
['kill', '-KILL', str(pid)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if not found_new:
break
def _popen(self, cmdline, **kwargs):
try:
return subprocess.Popen(cmdline, **kwargs)
except:
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.exception('Error running: %s' % (' '.join(cmdline)))
return None
def _call(self, cmdline, **kwargs):
try:
subprocess.check_call(cmdline, **kwargs)
except:
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.exception('Error running: %s' % (' '.join(cmdline)))
def set_terminate_child_processes(self, py_db, terminate_child_processes):
py_db.terminate_child_processes = terminate_child_processes
def set_terminate_keyboard_interrupt(self, py_db, terminate_keyboard_interrupt):
py_db.terminate_keyboard_interrupt = terminate_keyboard_interrupt
def terminate_process(self, py_db):
'''
Terminates the current process (and child processes if the option to also terminate
child processes is enabled).
'''
try:
if py_db.terminate_child_processes:
pydev_log.debug('Terminating child processes.')
if IS_WINDOWS:
self._terminate_child_processes_windows(py_db.dont_terminate_child_pids)
else:
self._terminate_child_processes_linux_and_mac(py_db.dont_terminate_child_pids)
finally:
pydev_log.debug('Exiting process (os._exit(0)).')
os._exit(0)
def _terminate_if_commands_processed(self, py_db):
py_db.dispose_and_kill_all_pydevd_threads()
self.terminate_process(py_db)
def request_terminate_process(self, py_db):
if py_db.terminate_keyboard_interrupt:
if not py_db.keyboard_interrupt_requested:
py_db.keyboard_interrupt_requested = True
interrupt_main_thread()
return
# We mark with a terminate_requested to avoid that paused threads start running
# (we should terminate as is without letting any paused thread run).
py_db.terminate_requested = True
run_as_pydevd_daemon_thread(py_db, self._terminate_if_commands_processed, py_db)
def setup_auto_reload_watcher(self, py_db, enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns):
py_db.setup_auto_reload_watcher(enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns)
clear_thread_local_info = None
The provided code snippet includes necessary dependencies for implementing the `settrace_forked` function. Write a Python function `def settrace_forked(setup_tracing=True)` to solve the following problem:
When creating a fork from a process in the debugger, we need to reset the whole debugger environment!
Here is the function:
def settrace_forked(setup_tracing=True):
'''
When creating a fork from a process in the debugger, we need to reset the whole debugger environment!
'''
from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder
py_db = GlobalDebuggerHolder.global_dbg
if py_db is not None:
py_db.created_pydb_daemon_threads = {} # Just making sure we won't touch those (paused) threads.
py_db = None
GlobalDebuggerHolder.global_dbg = None
threading.current_thread().additional_info = None
# Make sure that we keep the same access tokens for subprocesses started through fork.
setup = SetupHolder.setup
if setup is None:
setup = {}
else:
# i.e.: Get the ppid at this point as it just changed.
# If we later do an exec() it should remain the same ppid.
setup[pydevd_constants.ARGUMENT_PPID] = PyDevdAPI().get_ppid()
access_token = setup.get('access-token')
client_access_token = setup.get('client-access-token')
if setup_tracing:
from _pydevd_frame_eval.pydevd_frame_eval_main import clear_thread_local_info
host, port = dispatch()
import pydevd_tracing
pydevd_tracing.restore_sys_set_trace_func()
if setup_tracing:
if port is not None:
custom_frames_container_init()
if clear_thread_local_info is not None:
clear_thread_local_info()
settrace(
host,
port=port,
suspend=False,
trace_only_current_thread=False,
overwrite_prev_trace=True,
patch_multiprocessing=True,
access_token=access_token,
client_access_token=client_access_token,
) | When creating a fork from a process in the debugger, we need to reset the whole debugger environment! |
177,867 | import sys
import os
try:
# Just empty packages to check if they're in the PYTHONPATH.
import _pydev_bundle
except ImportError:
# On the first import of a pydevd module, add pydevd itself to the PYTHONPATH
# if its dependencies cannot be imported.
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import _pydev_bundle
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
The provided code snippet includes necessary dependencies for implementing the `skip_subprocess_arg_patch` function. Write a Python function `def skip_subprocess_arg_patch()` to solve the following problem:
May be used to skip the monkey-patching that pydevd does to skip changing arguments to embed the debugger into child processes. i.e.: with pydevd.skip_subprocess_arg_patch(): subprocess.call(...)
Here is the function:
def skip_subprocess_arg_patch():
'''
May be used to skip the monkey-patching that pydevd does to
skip changing arguments to embed the debugger into child processes.
i.e.:
with pydevd.skip_subprocess_arg_patch():
subprocess.call(...)
'''
from _pydev_bundle import pydev_monkey
with pydev_monkey.skip_subprocess_arg_patch():
yield | May be used to skip the monkey-patching that pydevd does to skip changing arguments to embed the debugger into child processes. i.e.: with pydevd.skip_subprocess_arg_patch(): subprocess.call(...) |
177,868 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
The provided code snippet includes necessary dependencies for implementing the `add_dont_terminate_child_pid` function. Write a Python function `def add_dont_terminate_child_pid(pid)` to solve the following problem:
May be used to ask pydevd to skip the termination of some process when it's asked to terminate (debug adapter protocol only). :param int pid: The pid to be ignored. i.e.: process = subprocess.Popen(...) pydevd.add_dont_terminate_child_pid(process.pid)
Here is the function:
def add_dont_terminate_child_pid(pid):
'''
May be used to ask pydevd to skip the termination of some process
when it's asked to terminate (debug adapter protocol only).
:param int pid:
The pid to be ignored.
i.e.:
process = subprocess.Popen(...)
pydevd.add_dont_terminate_child_pid(process.pid)
'''
py_db = get_global_debugger()
if py_db is not None:
py_db.dont_terminate_child_pids.add(pid) | May be used to ask pydevd to skip the termination of some process when it's asked to terminate (debug adapter protocol only). :param int pid: The pid to be ignored. i.e.: process = subprocess.Popen(...) pydevd.add_dont_terminate_child_pid(process.pid) |
177,869 | import sys
if sys.version_info[:2] < (3, 6):
raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.')
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
def enable_qt_support(qt_support_mode):
from _pydev_bundle import pydev_monkey_qt
pydev_monkey_qt.patch_qt(qt_support_mode)
class SignatureFactory(object):
def __init__(self):
self._caller_cache = {}
self.cache = CallSignatureCache()
def create_signature(self, frame, filename, with_args=True):
try:
_, modulename, funcname = self.file_module_function_of(frame)
signature = Signature(filename, funcname)
if with_args:
signature.set_args(frame, recursive=True)
return signature
except:
pydev_log.exception()
def file_module_function_of(self, frame): # this code is take from trace module and fixed to work with new-style classes
code = frame.f_code
filename = code.co_filename
if filename:
modulename = _modname(filename)
else:
modulename = None
funcname = code.co_name
clsname = None
if code in self._caller_cache:
if self._caller_cache[code] is not None:
clsname = self._caller_cache[code]
else:
self._caller_cache[code] = None
clsname = get_clsname_for_code(code, frame)
if clsname is not None:
# cache the result - assumption is that new.* is
# not called later to disturb this relationship
# _caller_cache could be flushed if functions in
# the new module get called.
self._caller_cache[code] = clsname
if clsname is not None:
funcname = "%s.%s" % (clsname, funcname)
return filename, modulename, funcname
The provided code snippet includes necessary dependencies for implementing the `apply_debugger_options` function. Write a Python function `def apply_debugger_options(setup_options)` to solve the following problem:
:type setup_options: dict[str, bool]
Here is the function:
def apply_debugger_options(setup_options):
"""
:type setup_options: dict[str, bool]
"""
default_options = {'save-signatures': False, 'qt-support': ''}
default_options.update(setup_options)
setup_options = default_options
debugger = get_global_debugger()
if setup_options['save-signatures']:
if pydevd_vm_type.get_vm_type() == pydevd_vm_type.PydevdVmType.JYTHON:
sys.stderr.write("Collecting run-time type information is not supported for Jython\n")
else:
# Only import it if we're going to use it!
from _pydevd_bundle.pydevd_signature import SignatureFactory
debugger.signature_factory = SignatureFactory()
if setup_options['qt-support']:
enable_qt_support(setup_options['qt-support']) | :type setup_options: dict[str, bool] |
177,870 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT)
pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__))
pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
The provided code snippet includes necessary dependencies for implementing the `log_to` function. Write a Python function `def log_to(log_file:str, log_level=3) -> None` to solve the following problem:
In pydevd it's possible to log by setting the following environment variables: PYDEVD_DEBUG=1 (sets the default log level to 3 along with other default options) PYDEVD_DEBUG_FILE=</path/to/file.log> Note that the file will have the pid of the process added to it (so, logging to /path/to/file.log would actually start logging to /path/to/file.<pid>.log -- if subprocesses are logged, each new subprocess will have the logging set to its own pid). Usually setting the environment variable is preferred as it'd log information while pydevd is still doing its imports and not just after this method is called, but on cases where this is hard to do this function may be called to set the tracing after pydevd itself is already imported.
Here is the function:
def log_to(log_file:str, log_level=3) -> None:
'''
In pydevd it's possible to log by setting the following environment variables:
PYDEVD_DEBUG=1 (sets the default log level to 3 along with other default options)
PYDEVD_DEBUG_FILE=</path/to/file.log>
Note that the file will have the pid of the process added to it (so, logging to
/path/to/file.log would actually start logging to /path/to/file.<pid>.log -- if subprocesses are
logged, each new subprocess will have the logging set to its own pid).
Usually setting the environment variable is preferred as it'd log information while
pydevd is still doing its imports and not just after this method is called, but on
cases where this is hard to do this function may be called to set the tracing after
pydevd itself is already imported.
'''
pydev_log.log_to(log_file, log_level) | In pydevd it's possible to log by setting the following environment variables: PYDEVD_DEBUG=1 (sets the default log level to 3 along with other default options) PYDEVD_DEBUG_FILE=</path/to/file.log> Note that the file will have the pid of the process added to it (so, logging to /path/to/file.log would actually start logging to /path/to/file.<pid>.log -- if subprocesses are logged, each new subprocess will have the logging set to its own pid). Usually setting the environment variable is preferred as it'd log information while pydevd is still doing its imports and not just after this method is called, but on cases where this is hard to do this function may be called to set the tracing after pydevd itself is already imported. |
177,871 | import sys
if sys.version_info[:2] < (3, 6):
raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.')
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
pydevd_gevent_integration = None
if SUPPORT_GEVENT:
try:
from _pydevd_bundle import pydevd_gevent_integration
except:
pydev_log.exception(
'pydevd: GEVENT_SUPPORT is set but gevent is not available in the environment.\n'
'Please unset GEVENT_SUPPORT from the environment variables or install gevent.')
else:
pydevd_gevent_integration.log_gevent_debug_info()
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT)
pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__))
pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
SUPPORT_GEVENT = is_true_in_env('GEVENT_SUPPORT')
def _log_initial_info():
pydev_log.debug("Initial arguments: %s", (sys.argv,))
pydev_log.debug("Current pid: %s", os.getpid())
pydev_log.debug("Using cython: %s", USING_CYTHON)
pydev_log.debug("Using frame eval: %s", USING_FRAME_EVAL)
pydev_log.debug("Using gevent mode: %s / imported gevent module support: %s", SUPPORT_GEVENT, bool(pydevd_gevent_integration)) | null |
177,872 | import sys
import os
from _pydevd_bundle import pydevd_constants
import atexit
import dis
import io
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import itertools
import traceback
import weakref
import getpass as getpass_mod
import functools
import pydevd_file_utils
from _pydev_bundle import pydev_imports, pydev_log
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_bundle.pydev_override import overrides
from _pydev_bundle._pydev_saved_modules import threading, time, thread
from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
from _pydevd_bundle import pydevd_utils
from _pydevd_bundle import pydevd_runpy
from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info
from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK,
CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE,
CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE,
CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE)
from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id,
DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame,
clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL,
NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once,
ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT,
PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame
from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
from _pydevd_bundle.pydevd_trace_dispatch import (
trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func, USING_CYTHON)
from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \
import_attr_from_module
from _pydevd_frame_eval.pydevd_frame_eval_main import (
frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL)
import pydev_ipython
from _pydevd_bundle.pydevd_source_mapping import SourceMapping
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER
from pydevd_file_utils import get_fullname, get_package_dir
from os.path import abspath as os_path_abspath
import pydevd_tracing
from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread,
create_server_socket, FSNotifyThread)
from _pydevd_bundle.pydevd_comm import(InternalConsoleExec,
_queue, ReaderThread, GetGlobalDebugger, get_global_debugger,
set_global_debugger, WriterThread,
start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace,
InternalSendCurrExceptionTraceProceeded)
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
from _pydevd_bundle.pydevd_process_net_command import process_net_command
from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
from socket import SHUT_RDWR
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_timeout import TimeoutTracker
from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
from _pydevd_bundle.pydevd_plugin_utils import PluginManager
pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT)
pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__))
pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
class PydevdCustomization(object):
def config(protocol='', debug_mode='', preimport=''):
pydev_log.debug('Config: protocol: %s, debug_mode: %s, preimport: %s', protocol, debug_mode, preimport)
PydevdCustomization.DEFAULT_PROTOCOL = protocol
PydevdCustomization.DEBUG_MODE = debug_mode
PydevdCustomization.PREIMPORT = preimport | null |
177,873 | import dis
import inspect
import opcode as _opcode
import struct
import sys
import types
from _pydevd_frame_eval.vendored import bytecode as _bytecode
from _pydevd_frame_eval.vendored.bytecode.instr import (
UNSET,
Instr,
Label,
SetLineno,
FreeVar,
CellVar,
Compare,
const_key,
_check_arg_int,
)
def _set_docstring(code, consts):
if not consts:
return
first_const = consts[0]
if isinstance(first_const, str) or first_const is None:
code.docstring = first_const | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.