id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
177,573 | import sqlite3
import datetime
import warnings
from sqlalchemy import create_engine, Column, ForeignKey, Sequence
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.interfaces import PoolListener
from sqlalchemy.orm import sessionmaker, deferred
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.types import Integer, BigInteger, Boolean, DateTime, String, \
LargeBinary, Enum, VARCHAR
from sqlalchemy.sql.expression import asc, desc
from crash import Crash, Marshaller, pickle, HIGHEST_PROTOCOL
from textio import CrashDump
import win32
The provided code snippet includes necessary dependencies for implementing the `_compile_varchar_mysql` function. Write a Python function `def _compile_varchar_mysql(element, compiler, **kw)` to solve the following problem:
MySQL hack to avoid the "VARCHAR requires a length" error.
Here is the function:
def _compile_varchar_mysql(element, compiler, **kw):
"""MySQL hack to avoid the "VARCHAR requires a length" error."""
if not element.length or element.length == 'max':
return "TEXT"
else:
return compiler.visit_VARCHAR(element, **kw) | MySQL hack to avoid the "VARCHAR requires a length" error. |
177,574 | import sqlite3
import datetime
import warnings
from sqlalchemy import create_engine, Column, ForeignKey, Sequence
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.interfaces import PoolListener
from sqlalchemy.orm import sessionmaker, deferred
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.types import Integer, BigInteger, Boolean, DateTime, String, \
LargeBinary, Enum, VARCHAR
from sqlalchemy.sql.expression import asc, desc
from crash import Crash, Marshaller, pickle, HIGHEST_PROTOCOL
from textio import CrashDump
import win32
The provided code snippet includes necessary dependencies for implementing the `Transactional` function. Write a Python function `def Transactional(fn, self, *argv, **argd)` to solve the following problem:
Decorator that wraps DAO methods to handle transactions automatically. It may only work with subclasses of L{BaseDAO}.
Here is the function:
def Transactional(fn, self, *argv, **argd):
"""
Decorator that wraps DAO methods to handle transactions automatically.
It may only work with subclasses of L{BaseDAO}.
"""
return self._transactional(fn, *argv, **argd) | Decorator that wraps DAO methods to handle transactions automatically. It may only work with subclasses of L{BaseDAO}. |
177,575 | import sqlite3
import datetime
import warnings
from sqlalchemy import create_engine, Column, ForeignKey, Sequence
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.interfaces import PoolListener
from sqlalchemy.orm import sessionmaker, deferred
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.types import Integer, BigInteger, Boolean, DateTime, String, \
LargeBinary, Enum, VARCHAR
from sqlalchemy.sql.expression import asc, desc
from crash import Crash, Marshaller, pickle, HIGHEST_PROTOCOL
from textio import CrashDump
import win32
def _gen_valid_access_flags():
f = []
for a1 in ("---", "R--", "RW-", "RC-", "--X", "R-X", "RWX", "RCX", "???"):
for a2 in ("G", "-"):
for a3 in ("N", "-"):
for a4 in ("W", "-"):
f.append("%s %s%s%s" % (a1, a2, a3, a4))
return tuple(f) | null |
177,576 | import sys
import types
def itervalues(d, **kw):
if hasattr(d, 'itervalues'):
return iter(d.itervalues(**kw))
return iter(d.values(**kw)) | null |
177,577 | import sys
import types
def iterlists(d, **kw):
if hasattr(d, 'iterlists'):
return iter(d.iterlists(**kw))
return iter(d.lists(**kw)) | null |
177,578 | import sys
import types
def itervalues(d, **kw):
return iter(d.itervalues(**kw)) | null |
177,579 | import sys
import types
def iterlists(d, **kw):
return iter(d.iterlists(**kw)) | null |
177,580 | import sys
import types
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value | null |
177,581 | import sys
import types
The provided code snippet includes necessary dependencies for implementing the `exec_` function. Write a Python function `def exec_(_code_, _globs_=None, _locs_=None)` to solve the following problem:
Execute code in a namespace.
Here is the function:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""") | Execute code in a namespace. |
177,582 | import sys
import types
def b(s):
if isinstance(s, str):
return s.encode("latin-1")
assert isinstance(s, bytes)
return s | null |
177,583 | import sys
import types
def u(s):
return s | null |
177,584 | import sys
import types
def int2byte(i):
return bytes((i,)) | null |
177,585 | import sys
import types
def b(s):
return s | null |
177,586 | import sys
import types
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") | null |
177,587 | import sys
import types
def byte2int(bs):
return ord(bs[0]) | null |
177,588 | import sys
import types
def indexbytes(buf, i):
return ord(buf[i]) | null |
177,589 | import sys
import types
def iterbytes(buf):
return (ord(byte) for byte in buf) | null |
177,590 |
def load_lib_and_attach(debugger, command, result, internal_dict):
import shlex
args = shlex.split(command)
dll = args[0]
is_debug = args[1]
python_code = args[2]
show_debug_info = args[3]
import lldb
options = lldb.SBExpressionOptions()
options.SetFetchDynamicValue()
options.SetTryAllThreads(run_others=False)
options.SetTimeoutInMicroSeconds(timeout=10000000)
print(dll)
target = debugger.GetSelectedTarget()
res = target.EvaluateExpression("(void*)dlopen(\"%s\", 2);" % (
dll), options)
error = res.GetError()
if error:
print(error)
print(python_code)
res = target.EvaluateExpression("(int)DoAttach(%s, \"%s\", %s);" % (
is_debug, python_code.replace('"', "'"), show_debug_info), options)
error = res.GetError()
if error:
print(error) | null |
177,591 |
def __lldb_init_module(debugger, internal_dict):
import lldb
debugger.HandleCommand('command script add -f lldb_prepare.load_lib_and_attach load_lib_and_attach')
try:
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
for thread in process:
# print('Marking process thread %d'%thread.GetThreadID())
internal_dict['_thread_%d' % thread.GetThreadID()] = True
# thread.Suspend()
except:
import traceback;traceback.print_exc() | null |
177,592 | def fix_main_thread_id(on_warn=lambda msg:None, on_exception=lambda msg:None, on_critical=lambda msg:None):
# This means that we weren't able to import threading in the main thread (which most
# likely means that the main thread is paused or in some very long operation).
# In this case we'll import threading here and hotfix what may be wrong in the threading
# module (if we're on Windows where we create a thread to do the attach and on Linux
# we are not certain on which thread we're executing this code).
#
# The code below is a workaround for https://bugs.python.org/issue37416
import sys
import threading
try:
with threading._active_limbo_lock:
main_thread_instance = get_main_thread_instance(threading)
if sys.platform == 'win32':
# On windows this code would be called in a secondary thread, so,
# the current thread is unlikely to be the main thread.
if hasattr(threading, '_get_ident'):
unlikely_thread_id = threading._get_ident() # py2
else:
unlikely_thread_id = threading.get_ident() # py3
else:
unlikely_thread_id = None
main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id)
if main_thread_id is not None:
main_thread_id_attr = '_ident'
if not hasattr(main_thread_instance, main_thread_id_attr):
main_thread_id_attr = '_Thread__ident'
assert hasattr(main_thread_instance, main_thread_id_attr)
if main_thread_id != getattr(main_thread_instance, main_thread_id_attr):
# Note that we also have to reset the '_tstack_lock' for a regular lock.
# This is needed to avoid an error on shutdown because this lock is bound
# to the thread state and will be released when the secondary thread
# that initialized the lock is finished -- making an assert fail during
# process shutdown.
main_thread_instance._tstate_lock = threading._allocate_lock()
main_thread_instance._tstate_lock.acquire()
# Actually patch the thread ident as well as the threading._active dict
# (we should have the _active_limbo_lock to do that).
threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None)
setattr(main_thread_instance, main_thread_id_attr, main_thread_id)
threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance
# Note: only import from pydevd after the patching is done (we want to do the minimum
# possible when doing that patching).
on_warn('The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416.')
if critical_warning:
on_critical('Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s' % (critical_warning,))
except:
on_exception('Error patching main thread id.')
def attach(port, host, protocol='', debug_mode=''):
try:
import sys
fix_main_thread = 'threading' not in sys.modules
if fix_main_thread:
def on_warn(msg):
from _pydev_bundle import pydev_log
pydev_log.warn(msg)
def on_exception(msg):
from _pydev_bundle import pydev_log
pydev_log.exception(msg)
def on_critical(msg):
from _pydev_bundle import pydev_log
pydev_log.critical(msg)
fix_main_thread_id(on_warn=on_warn, on_exception=on_exception, on_critical=on_critical)
else:
from _pydev_bundle import pydev_log # @Reimport
pydev_log.debug('The threading module is already imported by user code.')
if protocol:
from _pydevd_bundle import pydevd_defaults
pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol
if debug_mode:
from _pydevd_bundle import pydevd_defaults
pydevd_defaults.PydevdCustomization.DEBUG_MODE = debug_mode
import pydevd
# I.e.: disconnect/reset if already connected.
pydevd.SetupHolder.setup = None
py_db = pydevd.get_global_debugger()
if py_db is not None:
py_db.dispose_and_kill_all_pydevd_threads(wait=False)
# pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3
pydevd.settrace(
port=port,
host=host,
stdoutToServer=True,
stderrToServer=True,
overwrite_prev_trace=True,
suspend=False,
trace_only_current_thread=False,
patch_multiprocessing=False,
)
except:
import traceback
traceback.print_exc() | null |
177,593 | from _pydevd_bundle.pydevd_constants import get_frame, IS_CPYTHON, IS_64BIT_PROCESS, IS_WINDOWS, \
IS_LINUX, IS_MAC, DebugInfoHolder, LOAD_NATIVE_LIB_FLAG, \
ENV_FALSE_LOWER_VALUES, ForkSafeLock
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import pydev_log, pydev_monkey
import os.path
import platform
import ctypes
from io import StringIO
import sys
import traceback
_last_tracing_func_thread_local = threading.local()
def SetTrace(tracing_func):
_last_tracing_func_thread_local.tracing_func = tracing_func
if tracing_func is not None:
if set_trace_to_threads(tracing_func, thread_idents=[thread.get_ident()], create_dummy_thread=False) == 0:
# If we can use our own tracer instead of the one from sys.settrace, do it (the reason
# is that this is faster than the Python version because we don't call
# PyFrame_FastToLocalsWithError and PyFrame_LocalsToFast at each event!
# (the difference can be huge when checking line events on frames as the
# time increases based on the number of local variables in the scope)
# See: InternalCallTrampoline (on the C side) for details.
return
# If it didn't work (or if it was None), use the Python version.
set_trace = TracingFunctionHolder._original_tracing or sys.settrace
set_trace(tracing_func)
def reapply_settrace():
try:
tracing_func = _last_tracing_func_thread_local.tracing_func
except AttributeError:
return
else:
SetTrace(tracing_func) | null |
177,594 | from _pydevd_bundle.pydevd_constants import get_frame, IS_CPYTHON, IS_64BIT_PROCESS, IS_WINDOWS, \
IS_LINUX, IS_MAC, DebugInfoHolder, LOAD_NATIVE_LIB_FLAG, \
ENV_FALSE_LOWER_VALUES, ForkSafeLock
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import pydev_log, pydev_monkey
import os.path
import platform
import ctypes
from io import StringIO
import sys
import traceback
class TracingFunctionHolder:
def _internal_set_trace(tracing_func):
def replace_sys_set_trace_func():
if TracingFunctionHolder._original_tracing is None:
TracingFunctionHolder._original_tracing = sys.settrace
sys.settrace = _internal_set_trace | null |
177,595 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
IS_DJANGO19_OR_HIGHER = False
class DjangoLineBreakpoint(LineBreakpointWithLazyValidation):
def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False):
self.canonical_normalized_filename = canonical_normalized_filename
LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
def __str__(self):
return "DjangoLineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line)
def _init_plugin_breaks(pydb):
pydb.django_exception_break = {}
pydb.django_breakpoints = {}
pydb.django_validation_info = _DjangoValidationInfo()
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)
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None):
if type == 'django-line':
django_line_breakpoint = DjangoLineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
if not hasattr(pydb, 'django_breakpoints'):
_init_plugin_breaks(pydb)
if IS_DJANGO19_OR_HIGHER:
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION
django_line_breakpoint.add_breakpoint_result = add_breakpoint_result
django_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state
else:
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR
return django_line_breakpoint, pydb.django_breakpoints
return None | null |
177,596 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
IS_DJANGO19_OR_HIGHER = False
def _init_plugin_breaks(pydb):
pydb.django_exception_break = {}
pydb.django_breakpoints = {}
pydb.django_validation_info = _DjangoValidationInfo()
def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints):
if IS_DJANGO19_OR_HIGHER:
django_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename)
if not django_breakpoints_for_file:
return
if not hasattr(py_db, 'django_validation_info'):
_init_plugin_breaks(py_db)
# In general we validate the breakpoints only when the template is loaded, but if the template
# was already loaded, we can validate the breakpoints based on the last loaded value.
py_db.django_validation_info.verify_breakpoints_from_template_cached_lines(
py_db, canonical_normalized_filename, django_breakpoints_for_file) | null |
177,597 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def _init_plugin_breaks(pydb):
pydb.django_exception_break = {}
pydb.django_breakpoints = {}
pydb.django_validation_info = _DjangoValidationInfo()
def add_exception_breakpoint(plugin, pydb, type, exception):
if type == 'django':
if not hasattr(pydb, 'django_exception_break'):
_init_plugin_breaks(pydb)
pydb.django_exception_break[exception] = True
return True
return False | null |
177,598 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def remove_exception_breakpoint(plugin, pydb, type, exception):
if type == 'django':
try:
del pydb.django_exception_break[exception]
return True
except:
pass
return False | null |
177,599 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def remove_all_exception_breakpoints(plugin, pydb):
if hasattr(pydb, 'django_exception_break'):
pydb.django_exception_break = {}
return True
return False | null |
177,600 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def get_breakpoints(plugin, pydb, type):
if type == 'django-line':
return pydb.django_breakpoints
return None | null |
177,601 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
def change_variable(plugin, frame, attr, expression):
if isinstance(frame, DjangoTemplateFrame):
result = eval(expression, frame.f_globals, frame.f_locals)
frame._change_variable(attr, result)
return result
return False | null |
177,602 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def _is_django_render_call(frame, debug=False):
try:
name = frame.f_code.co_name
if name != 'render':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
inherits_node = _inherits(cls, 'Node')
if not inherits_node:
return False
clsname = cls.__name__
if IS_DJANGO19:
# in Django 1.9 we need to save the flag that there is included template
if clsname == 'IncludeNode':
if 'context' in frame.f_locals:
context = frame.f_locals['context']
context._has_included_template = True
return clsname not in _IGNORE_RENDER_OF_CLASSES
except:
pydev_log.exception()
return False
def can_skip(plugin, main_debugger, frame):
if main_debugger.django_breakpoints:
if _is_django_render_call(frame):
return False
if main_debugger.django_exception_break:
module_name = frame.f_globals.get('__name__', '')
if module_name == 'django.template.base':
# Exceptions raised at django.template.base must be checked.
return False
return True | null |
177,603 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def has_exception_breaks(plugin):
if len(plugin.main_debugger.django_exception_break) > 0:
return True
return False | null |
177,604 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def has_line_breaks(plugin):
for _canonical_normalized_filename, breakpoints in plugin.main_debugger.django_breakpoints.items():
if len(breakpoints) > 0:
return True
return False | null |
177,605 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def _is_django_render_call(frame, debug=False):
try:
name = frame.f_code.co_name
if name != 'render':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
inherits_node = _inherits(cls, 'Node')
if not inherits_node:
return False
clsname = cls.__name__
if IS_DJANGO19:
# in Django 1.9 we need to save the flag that there is included template
if clsname == 'IncludeNode':
if 'context' in frame.f_locals:
context = frame.f_locals['context']
context._has_included_template = True
return clsname not in _IGNORE_RENDER_OF_CLASSES
except:
pydev_log.exception()
return False
def _is_django_context_get_call(frame):
try:
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
return _inherits(cls, 'BaseContext')
except:
pydev_log.exception()
return False
def _is_django_resolve_call(frame):
try:
name = frame.f_code.co_name
if name != '_resolve_lookup':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
clsname = cls.__name__
return clsname == 'Variable'
except:
pydev_log.exception()
return False
def _is_django_suspended(thread):
return thread.additional_info.suspend_type == DJANGO_SUSPEND
def cmd_step_into(plugin, main_debugger, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
if _is_django_suspended(thread):
stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame)
plugin_stop = stop_info['django_stop']
stop = stop and _is_django_resolve_call(frame.f_back) and not _is_django_context_get_call(frame)
if stop:
info.pydev_django_resolve_frame = True # we remember that we've go into python code from django rendering frame
return stop, plugin_stop | null |
177,606 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def _is_django_render_call(frame, debug=False):
try:
name = frame.f_code.co_name
if name != 'render':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
inherits_node = _inherits(cls, 'Node')
if not inherits_node:
return False
clsname = cls.__name__
if IS_DJANGO19:
# in Django 1.9 we need to save the flag that there is included template
if clsname == 'IncludeNode':
if 'context' in frame.f_locals:
context = frame.f_locals['context']
context._has_included_template = True
return clsname not in _IGNORE_RENDER_OF_CLASSES
except:
pydev_log.exception()
return False
def _is_django_resolve_call(frame):
try:
name = frame.f_code.co_name
if name != '_resolve_lookup':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
clsname = cls.__name__
return clsname == 'Variable'
except:
pydev_log.exception()
return False
def _is_django_suspended(thread):
return thread.additional_info.suspend_type == DJANGO_SUSPEND
DJANGO_SUSPEND = 2
def cmd_step_over(plugin, main_debugger, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
if _is_django_suspended(thread):
stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame)
plugin_stop = stop_info['django_stop']
stop = False
return stop, plugin_stop
else:
if event == 'return' and info.pydev_django_resolve_frame and _is_django_resolve_call(frame.f_back):
# we return to Django suspend mode and should not stop before django rendering frame
info.pydev_step_stop = frame.f_back
info.pydev_django_resolve_frame = False
thread.additional_info.suspend_type = DJANGO_SUSPEND
stop = info.pydev_step_stop is frame and event in ('line', 'return')
return stop, plugin_stop | null |
177,607 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def suspend_django(main_debugger, thread, frame, cmd=CMD_SET_BREAK):
if frame.f_lineno is None:
return None
main_debugger.set_suspend(thread, cmd)
thread.additional_info.suspend_type = DJANGO_SUSPEND
return frame
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
def stop(plugin, main_debugger, frame, event, args, stop_info, arg, step_cmd):
main_debugger = args[0]
thread = args[3]
if 'django_stop' in stop_info and stop_info['django_stop']:
frame = suspend_django(main_debugger, thread, DjangoTemplateFrame(frame), step_cmd)
if frame:
main_debugger.do_wait_suspend(thread, frame, event, arg)
return True
return False | null |
177,608 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
IS_DJANGO19_OR_HIGHER = False
def _is_django_render_call(frame, debug=False):
try:
name = frame.f_code.co_name
if name != 'render':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
inherits_node = _inherits(cls, 'Node')
if not inherits_node:
return False
clsname = cls.__name__
if IS_DJANGO19:
# in Django 1.9 we need to save the flag that there is included template
if clsname == 'IncludeNode':
if 'context' in frame.f_locals:
context = frame.f_locals['context']
context._has_included_template = True
return clsname not in _IGNORE_RENDER_OF_CLASSES
except:
pydev_log.exception()
return False
def _get_template_original_file_name_from_frame(frame):
try:
if IS_DJANGO19:
# The Node source was removed since Django 1.9
if 'context' in frame.f_locals:
context = frame.f_locals['context']
if hasattr(context, '_has_included_template'):
# if there was included template we need to inspect the previous frames and find its name
back = frame.f_back
while back is not None and frame.f_code.co_name in ('render', '_render'):
locals = back.f_locals
if 'self' in locals:
self = locals['self']
if self.__class__.__name__ == 'Template' and hasattr(self, 'origin') and \
hasattr(self.origin, 'name'):
return _convert_to_str(self.origin.name)
back = back.f_back
else:
if hasattr(context, 'template') and hasattr(context.template, 'origin') and \
hasattr(context.template.origin, 'name'):
return _convert_to_str(context.template.origin.name)
return None
elif IS_DJANGO19_OR_HIGHER:
# For Django 1.10 and later there is much simpler way to get template name
if 'self' in frame.f_locals:
self = frame.f_locals['self']
if hasattr(self, 'origin') and hasattr(self.origin, 'name'):
return _convert_to_str(self.origin.name)
return None
source = _get_source_django_18_or_lower(frame)
if source is None:
pydev_log.debug("Source is None\n")
return None
fname = _convert_to_str(source[0].name)
if fname == '<unknown source>':
pydev_log.debug("Source name is %s\n" % fname)
return None
else:
return fname
except:
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2:
pydev_log.exception('Error getting django template filename.')
return None
def _get_template_line(frame):
if IS_DJANGO19_OR_HIGHER:
node = frame.f_locals['self']
if hasattr(node, 'token') and hasattr(node.token, 'lineno'):
return node.token.lineno
else:
return None
source = _get_source_django_18_or_lower(frame)
original_filename = _get_template_original_file_name_from_frame(frame)
if original_filename is not None:
try:
absolute_filename = absolute_path(original_filename)
return _offset_to_line_number(_read_file(absolute_filename), source[1][0])
except:
return None
return None
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
STATE_SUSPEND = 2
def canonical_normalized_path(filename):
'''
This returns a filename that is canonical and it's meant to be used internally
to store information on breakpoints and see if there's any hit on it.
Note that this version is only internal as it may not match the case and
may have symlinks resolved (and thus may not match what the user expects
in the editor).
'''
return get_abs_path_real_path_and_base_from_file(filename)[1]
def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args):
py_db = args[0]
_filename = args[1]
info = args[2]
breakpoint_type = 'django'
if event == 'call' and info.pydev_state != STATE_SUSPEND and py_db.django_breakpoints and _is_django_render_call(frame):
original_filename = _get_template_original_file_name_from_frame(frame)
pydev_log.debug("Django is rendering a template: %s", original_filename)
canonical_normalized_filename = canonical_normalized_path(original_filename)
django_breakpoints_for_file = py_db.django_breakpoints.get(canonical_normalized_filename)
if django_breakpoints_for_file:
# At this point, let's validate whether template lines are correct.
if IS_DJANGO19_OR_HIGHER:
django_validation_info = py_db.django_validation_info
context = frame.f_locals['context']
django_template = context.template
django_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, django_breakpoints_for_file, django_template)
pydev_log.debug("Breakpoints for that file: %s", django_breakpoints_for_file)
template_line = _get_template_line(frame)
pydev_log.debug("Tracing template line: %s", template_line)
if template_line in django_breakpoints_for_file:
django_breakpoint = django_breakpoints_for_file[template_line]
new_frame = DjangoTemplateFrame(frame)
return True, django_breakpoint, new_frame, breakpoint_type
return False, None, None, breakpoint_type | null |
177,609 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def suspend_django(main_debugger, thread, frame, cmd=CMD_SET_BREAK):
if frame.f_lineno is None:
return None
main_debugger.set_suspend(thread, cmd)
thread.additional_info.suspend_type = DJANGO_SUSPEND
return frame
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
def suspend(plugin, main_debugger, thread, frame, bp_type):
if bp_type == 'django':
return suspend_django(main_debugger, thread, DjangoTemplateFrame(frame))
return None | null |
177,610 | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
def suspend_django(main_debugger, thread, frame, cmd=CMD_SET_BREAK):
if frame.f_lineno is None:
return None
main_debugger.set_suspend(thread, cmd)
thread.additional_info.suspend_type = DJANGO_SUSPEND
return frame
def _find_django_render_frame(frame):
while frame is not None and not _is_django_render_call(frame):
frame = frame.f_back
return frame
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
class DjangoTemplateSyntaxErrorFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, original_filename, lineno, f_locals):
self.f_code = FCode('Django TemplateSyntaxError', original_filename)
self.f_lineno = lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = f_locals
self.f_trace = None
def _is_django_variable_does_not_exist_exception_break_context(frame):
try:
name = frame.f_code.co_name
except:
name = None
return name in ('_resolve_lookup', 'find_template')
def _is_ignoring_failures(frame):
while frame is not None:
if frame.f_code.co_name == 'resolve':
ignore_failures = frame.f_locals.get('ignore_failures')
if ignore_failures:
return True
frame = frame.f_back
return False
def _get_original_filename_from_origin_in_parent_frame_locals(frame, parent_frame_name):
filename = None
parent_frame = frame
while parent_frame.f_code.co_name != parent_frame_name:
parent_frame = parent_frame.f_back
origin = None
if parent_frame is not None:
origin = parent_frame.f_locals.get('origin')
if hasattr(origin, 'name') and origin.name is not None:
filename = _convert_to_str(origin.name)
return filename
def add_exception_to_frame(frame, exception_info):
frame.f_locals['__exception__'] = exception_info
def just_raised(trace):
if trace is None:
return False
return trace.tb_next is None
def ignore_exception_trace(trace):
while trace is not None:
filename = trace.tb_frame.f_code.co_filename
if filename in (
'<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>'):
# Do not stop on inner exceptions in py3 while importing
return True
# ImportError should appear in a user's code, not inside debugger
for file in FILES_WITH_IMPORT_HOOKS:
if filename.endswith(file):
return True
trace = trace.tb_next
return False
def exception_break(plugin, main_debugger, pydb_frame, frame, args, arg):
main_debugger = args[0]
thread = args[3]
exception, value, trace = arg
if main_debugger.django_exception_break and exception is not None:
if exception.__name__ in ['VariableDoesNotExist', 'TemplateDoesNotExist', 'TemplateSyntaxError'] and \
just_raised(trace) and not ignore_exception_trace(trace):
if exception.__name__ == 'TemplateSyntaxError':
# In this case we don't actually have a regular render frame with the context
# (we didn't really get to that point).
token = getattr(value, 'token', None)
if token is None:
# Django 1.7 does not have token in exception. Try to get it from locals.
token = frame.f_locals.get('token')
lineno = getattr(token, 'lineno', None)
original_filename = None
if lineno is not None:
original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'get_template')
if original_filename is None:
# Django 1.7 does not have origin in get_template. Try to get it from
# load_template.
original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'load_template')
if original_filename is not None and lineno is not None:
syntax_error_frame = DjangoTemplateSyntaxErrorFrame(
frame, original_filename, lineno, {'token': token, 'exception': exception})
suspend_frame = suspend_django(
main_debugger, thread, syntax_error_frame, CMD_ADD_EXCEPTION_BREAK)
return True, suspend_frame
elif exception.__name__ == 'VariableDoesNotExist':
if _is_django_variable_does_not_exist_exception_break_context(frame):
if not getattr(exception, 'silent_variable_failure', False) and not _is_ignoring_failures(frame):
render_frame = _find_django_render_frame(frame)
if render_frame:
suspend_frame = suspend_django(
main_debugger, thread, DjangoTemplateFrame(render_frame), CMD_ADD_EXCEPTION_BREAK)
if suspend_frame:
add_exception_to_frame(suspend_frame, (exception, value, trace))
thread.additional_info.pydev_message = 'VariableDoesNotExist'
suspend_frame.f_back = frame
frame = suspend_frame
return True, frame
return None | null |
177,611 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
class Jinja2LineBreakpoint(LineBreakpointWithLazyValidation):
def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False):
self.canonical_normalized_filename = canonical_normalized_filename
LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
def __str__(self):
return "Jinja2LineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line)
def _init_plugin_breaks(pydb):
pydb.jinja2_exception_break = {}
pydb.jinja2_breakpoints = {}
pydb.jinja2_validation_info = _Jinja2ValidationInfo()
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)
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None):
if type == 'jinja2-line':
jinja2_line_breakpoint = Jinja2LineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
if not hasattr(pydb, 'jinja2_breakpoints'):
_init_plugin_breaks(pydb)
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION
jinja2_line_breakpoint.add_breakpoint_result = add_breakpoint_result
jinja2_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state
return jinja2_line_breakpoint, pydb.jinja2_breakpoints
return None | null |
177,612 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _init_plugin_breaks(pydb):
pydb.jinja2_exception_break = {}
pydb.jinja2_breakpoints = {}
pydb.jinja2_validation_info = _Jinja2ValidationInfo()
def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints):
jinja2_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename)
if not jinja2_breakpoints_for_file:
return
if not hasattr(py_db, 'jinja2_validation_info'):
_init_plugin_breaks(py_db)
# In general we validate the breakpoints only when the template is loaded, but if the template
# was already loaded, we can validate the breakpoints based on the last loaded value.
py_db.jinja2_validation_info.verify_breakpoints_from_template_cached_lines(
py_db, canonical_normalized_filename, jinja2_breakpoints_for_file) | null |
177,613 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _init_plugin_breaks(pydb):
pydb.jinja2_exception_break = {}
pydb.jinja2_breakpoints = {}
pydb.jinja2_validation_info = _Jinja2ValidationInfo()
def add_exception_breakpoint(plugin, pydb, type, exception):
if type == 'jinja2':
if not hasattr(pydb, 'jinja2_exception_break'):
_init_plugin_breaks(pydb)
pydb.jinja2_exception_break[exception] = True
return True
return False | null |
177,614 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def remove_all_exception_breakpoints(plugin, pydb):
if hasattr(pydb, 'jinja2_exception_break'):
pydb.jinja2_exception_break = {}
return True
return False | null |
177,615 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def remove_exception_breakpoint(plugin, pydb, type, exception):
if type == 'jinja2':
try:
del pydb.jinja2_exception_break[exception]
return True
except:
pass
return False | null |
177,616 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def get_breakpoints(plugin, pydb, type):
if type == 'jinja2-line':
return pydb.jinja2_breakpoints
return None | null |
177,617 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
class Jinja2TemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, original_filename=None, template_lineno=None):
if original_filename is None:
original_filename = _get_jinja2_template_original_filename(frame)
if template_lineno is None:
template_lineno = _get_jinja2_template_line(frame)
self.back_context = None
if 'context' in frame.f_locals:
# sometimes we don't have 'context', e.g. in macros
self.back_context = frame.f_locals['context']
self.f_code = FCode('template', original_filename)
self.f_lineno = template_lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = self.collect_context(frame)
self.f_trace = None
def _get_real_var_name(self, orig_name):
# replace leading number for local variables
parts = orig_name.split('_')
if len(parts) > 1 and parts[0].isdigit():
return parts[1]
return orig_name
def collect_context(self, frame):
res = {}
for k, v in frame.f_locals.items():
if not k.startswith('l_'):
res[k] = v
elif v and not _is_missing(v):
res[self._get_real_var_name(k[2:])] = v
if self.back_context is not None:
for k, v in self.back_context.items():
res[k] = v
return res
def _change_variable(self, frame, name, value):
in_vars_or_parents = False
if 'context' in frame.f_locals:
if name in frame.f_locals['context'].parent:
self.back_context.parent[name] = value
in_vars_or_parents = True
if name in frame.f_locals['context'].vars:
self.back_context.vars[name] = value
in_vars_or_parents = True
l_name = 'l_' + name
if l_name in frame.f_locals:
if in_vars_or_parents:
frame.f_locals[l_name] = self.back_context.resolve(name)
else:
frame.f_locals[l_name] = value
def change_variable(plugin, frame, attr, expression):
if isinstance(frame, Jinja2TemplateFrame):
result = eval(expression, frame.f_globals, frame.f_locals)
frame._change_variable(frame.f_back, attr, result)
return result
return False | null |
177,618 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _is_missing(item):
if item.__class__.__name__ == 'MissingType':
return True
return False | null |
177,619 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _find_render_function_frame(frame):
# in order to hide internal rendering functions
old_frame = frame
try:
while not ('self' in frame.f_locals and frame.f_locals['self'].__class__.__name__ == 'Template' and \
frame.f_code.co_name == 'render'):
frame = frame.f_back
if frame is None:
return old_frame
return frame
except:
return old_frame | null |
177,620 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def has_exception_breaks(plugin):
if len(plugin.main_debugger.jinja2_exception_break) > 0:
return True
return False | null |
177,621 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def has_line_breaks(plugin):
for _canonical_normalized_filename, breakpoints in plugin.main_debugger.jinja2_breakpoints.items():
if len(breakpoints) > 0:
return True
return False | null |
177,622 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _is_jinja2_render_call(frame):
def _get_jinja2_template_original_filename(frame):
def canonical_normalized_path(filename):
def can_skip(plugin, pydb, frame):
if pydb.jinja2_breakpoints and _is_jinja2_render_call(frame):
filename = _get_jinja2_template_original_filename(frame)
if filename is not None:
canonical_normalized_filename = canonical_normalized_path(filename)
jinja2_breakpoints_for_file = pydb.jinja2_breakpoints.get(canonical_normalized_filename)
if jinja2_breakpoints_for_file:
return False
if pydb.jinja2_exception_break:
name = frame.f_code.co_name
# errors in compile time
if name in ('template', 'top-level template code', '<module>') or name.startswith('block '):
f_back = frame.f_back
module_name = ''
if f_back is not None:
module_name = f_back.f_globals.get('__name__', '')
if module_name.startswith('jinja2.'):
return False
return True | null |
177,623 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _is_jinja2_render_call(frame):
def _is_jinja2_suspended(thread):
def _is_jinja2_context_call(frame):
def _is_jinja2_internal_function(frame):
JINJA2_SUSPEND = 3
def cmd_step_into(plugin, pydb, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
stop_info['jinja2_stop'] = False
if _is_jinja2_suspended(thread):
stop_info['jinja2_stop'] = event in ('call', 'line') and _is_jinja2_render_call(frame)
plugin_stop = stop_info['jinja2_stop']
stop = False
if info.pydev_call_from_jinja2 is not None:
if _is_jinja2_internal_function(frame):
# if internal Jinja2 function was called, we sould continue debugging inside template
info.pydev_call_from_jinja2 = None
else:
# we go into python code from Jinja2 rendering frame
stop = True
if event == 'call' and _is_jinja2_context_call(frame.f_back):
# we called function from context, the next step will be in function
info.pydev_call_from_jinja2 = 1
if event == 'return' and _is_jinja2_context_call(frame.f_back):
# we return from python code to Jinja2 rendering frame
info.pydev_step_stop = info.pydev_call_from_jinja2
info.pydev_call_from_jinja2 = None
thread.additional_info.suspend_type = JINJA2_SUSPEND
stop = False
# print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop_info", stop_info, \
# "thread.additional_info.suspend_type", thread.additional_info.suspend_type
# print "event", event, "farme.locals", frame.f_locals
return stop, plugin_stop | null |
177,624 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _is_jinja2_render_call(frame):
try:
name = frame.f_code.co_name
if "__jinja_template__" in frame.f_globals and name in ("root", "loop", "macro") or name.startswith("block_"):
return True
return False
except:
pydev_log.exception()
return False
def _is_jinja2_suspended(thread):
return thread.additional_info.suspend_type == JINJA2_SUSPEND
def _is_jinja2_context_call(frame):
return "_Context__obj" in frame.f_locals
def _find_jinja2_render_frame(frame):
while frame is not None and not _is_jinja2_render_call(frame):
frame = frame.f_back
return frame
JINJA2_SUSPEND = 3
def cmd_step_over(plugin, pydb, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
stop_info['jinja2_stop'] = False
if _is_jinja2_suspended(thread):
stop = False
if info.pydev_call_inside_jinja2 is None:
if _is_jinja2_render_call(frame):
if event == 'call':
info.pydev_call_inside_jinja2 = frame.f_back
if event in ('line', 'return'):
info.pydev_call_inside_jinja2 = frame
else:
if event == 'line':
if _is_jinja2_render_call(frame) and info.pydev_call_inside_jinja2 is frame:
stop_info['jinja2_stop'] = True
plugin_stop = stop_info['jinja2_stop']
if event == 'return':
if frame is info.pydev_call_inside_jinja2 and 'event' not in frame.f_back.f_locals:
info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame.f_back)
return stop, plugin_stop
else:
if event == 'return' and _is_jinja2_context_call(frame.f_back):
# we return from python code to Jinja2 rendering frame
info.pydev_call_from_jinja2 = None
info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame)
thread.additional_info.suspend_type = JINJA2_SUSPEND
stop = False
return stop, plugin_stop
# print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop", stop, "jinja_stop", jinja2_stop, \
# "thread.additional_info.suspend_type", thread.additional_info.suspend_type
# print "event", event, "info.pydev_call_inside_jinja2", info.pydev_call_inside_jinja2
# print "frame", frame, "frame.f_back", frame.f_back, "step_stop", info.pydev_step_stop
# print "is_context_call", _is_jinja2_context_call(frame)
# print "render", _is_jinja2_render_call(frame)
# print "-------------"
return stop, plugin_stop | null |
177,625 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _suspend_jinja2(pydb, thread, frame, cmd=CMD_SET_BREAK, message=None):
frame = Jinja2TemplateFrame(frame)
if frame.f_lineno is None:
return None
pydb.set_suspend(thread, cmd)
thread.additional_info.suspend_type = JINJA2_SUSPEND
if cmd == CMD_ADD_EXCEPTION_BREAK:
# send exception name as message
if message:
message = str(message)
thread.additional_info.pydev_message = message
return frame
def stop(plugin, pydb, frame, event, args, stop_info, arg, step_cmd):
pydb = args[0]
thread = args[3]
if 'jinja2_stop' in stop_info and stop_info['jinja2_stop']:
frame = _suspend_jinja2(pydb, thread, frame, step_cmd)
if frame:
pydb.do_wait_suspend(thread, frame, event, arg)
return True
return False | null |
177,626 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _is_jinja2_render_call(frame):
try:
name = frame.f_code.co_name
if "__jinja_template__" in frame.f_globals and name in ("root", "loop", "macro") or name.startswith("block_"):
return True
return False
except:
pydev_log.exception()
return False
class Jinja2TemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, original_filename=None, template_lineno=None):
if original_filename is None:
original_filename = _get_jinja2_template_original_filename(frame)
if template_lineno is None:
template_lineno = _get_jinja2_template_line(frame)
self.back_context = None
if 'context' in frame.f_locals:
# sometimes we don't have 'context', e.g. in macros
self.back_context = frame.f_locals['context']
self.f_code = FCode('template', original_filename)
self.f_lineno = template_lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = self.collect_context(frame)
self.f_trace = None
def _get_real_var_name(self, orig_name):
# replace leading number for local variables
parts = orig_name.split('_')
if len(parts) > 1 and parts[0].isdigit():
return parts[1]
return orig_name
def collect_context(self, frame):
res = {}
for k, v in frame.f_locals.items():
if not k.startswith('l_'):
res[k] = v
elif v and not _is_missing(v):
res[self._get_real_var_name(k[2:])] = v
if self.back_context is not None:
for k, v in self.back_context.items():
res[k] = v
return res
def _change_variable(self, frame, name, value):
in_vars_or_parents = False
if 'context' in frame.f_locals:
if name in frame.f_locals['context'].parent:
self.back_context.parent[name] = value
in_vars_or_parents = True
if name in frame.f_locals['context'].vars:
self.back_context.vars[name] = value
in_vars_or_parents = True
l_name = 'l_' + name
if l_name in frame.f_locals:
if in_vars_or_parents:
frame.f_locals[l_name] = self.back_context.resolve(name)
else:
frame.f_locals[l_name] = value
def _get_jinja2_template_line(frame):
debug_info = _get_jinja2_template_debug_info(frame)
if debug_info is None:
return None
lineno = frame.f_lineno
for pair in debug_info:
if pair[1] == lineno:
return pair[0]
return None
def _get_jinja2_template_original_filename(frame):
if '__jinja_template__' in frame.f_globals:
return _convert_to_str(frame.f_globals['__jinja_template__'].filename)
return None
STATE_SUSPEND = 2
def canonical_normalized_path(filename):
'''
This returns a filename that is canonical and it's meant to be used internally
to store information on breakpoints and see if there's any hit on it.
Note that this version is only internal as it may not match the case and
may have symlinks resolved (and thus may not match what the user expects
in the editor).
'''
return get_abs_path_real_path_and_base_from_file(filename)[1]
def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args):
py_db = args[0]
_filename = args[1]
info = args[2]
break_type = 'jinja2'
if event == 'line' and info.pydev_state != STATE_SUSPEND and py_db.jinja2_breakpoints and _is_jinja2_render_call(frame):
jinja_template = frame.f_globals.get('__jinja_template__')
if jinja_template is None:
return False, None, None, break_type
original_filename = _get_jinja2_template_original_filename(frame)
if original_filename is not None:
pydev_log.debug("Jinja2 is rendering a template: %s", original_filename)
canonical_normalized_filename = canonical_normalized_path(original_filename)
jinja2_breakpoints_for_file = py_db.jinja2_breakpoints.get(canonical_normalized_filename)
if jinja2_breakpoints_for_file:
jinja2_validation_info = py_db.jinja2_validation_info
jinja2_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, jinja2_breakpoints_for_file, jinja_template)
template_lineno = _get_jinja2_template_line(frame)
if template_lineno is not None:
jinja2_breakpoint = jinja2_breakpoints_for_file.get(template_lineno)
if jinja2_breakpoint is not None:
new_frame = Jinja2TemplateFrame(frame, original_filename, template_lineno)
return True, jinja2_breakpoint, new_frame, break_type
return False, None, None, break_type | null |
177,627 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _suspend_jinja2(pydb, thread, frame, cmd=CMD_SET_BREAK, message=None):
frame = Jinja2TemplateFrame(frame)
if frame.f_lineno is None:
return None
pydb.set_suspend(thread, cmd)
thread.additional_info.suspend_type = JINJA2_SUSPEND
if cmd == CMD_ADD_EXCEPTION_BREAK:
# send exception name as message
if message:
message = str(message)
thread.additional_info.pydev_message = message
return frame
def suspend(plugin, pydb, thread, frame, bp_type):
if bp_type == 'jinja2':
return _suspend_jinja2(pydb, thread, frame)
return None | null |
177,628 | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
def _suspend_jinja2(pydb, thread, frame, cmd=CMD_SET_BREAK, message=None):
frame = Jinja2TemplateFrame(frame)
if frame.f_lineno is None:
return None
pydb.set_suspend(thread, cmd)
thread.additional_info.suspend_type = JINJA2_SUSPEND
if cmd == CMD_ADD_EXCEPTION_BREAK:
# send exception name as message
if message:
message = str(message)
thread.additional_info.pydev_message = message
return frame
def _find_jinja2_render_frame(frame):
while frame is not None and not _is_jinja2_render_call(frame):
frame = frame.f_back
return frame
JINJA2_SUSPEND = 3
def add_exception_to_frame(frame, exception_info):
frame.f_locals['__exception__'] = exception_info
def exception_break(plugin, pydb, pydb_frame, frame, args, arg):
pydb = args[0]
thread = args[3]
exception, value, trace = arg
if pydb.jinja2_exception_break and exception is not None:
exception_type = list(pydb.jinja2_exception_break.keys())[0]
if exception.__name__ in ('UndefinedError', 'TemplateNotFound', 'TemplatesNotFound'):
# errors in rendering
render_frame = _find_jinja2_render_frame(frame)
if render_frame:
suspend_frame = _suspend_jinja2(pydb, thread, render_frame, CMD_ADD_EXCEPTION_BREAK, message=exception_type)
if suspend_frame:
add_exception_to_frame(suspend_frame, (exception, value, trace))
suspend_frame.f_back = frame
frame = suspend_frame
return True, frame
elif exception.__name__ in ('TemplateSyntaxError', 'TemplateAssertionError'):
name = frame.f_code.co_name
# errors in compile time
if name in ('template', 'top-level template code', '<module>') or name.startswith('block '):
f_back = frame.f_back
if f_back is not None:
module_name = f_back.f_globals.get('__name__', '')
if module_name.startswith('jinja2.'):
# Jinja2 translates exception info and creates fake frame on his own
pydb_frame.set_suspend(thread, CMD_ADD_EXCEPTION_BREAK)
add_exception_to_frame(frame, (exception, value, trace))
thread.additional_info.suspend_type = JINJA2_SUSPEND
thread.additional_info.pydev_message = str(exception_type)
return True, frame
return None | null |
177,629 | import sys
def find_cached_module(mod_name):
return sys.modules.get(mod_name, None)
def find_mod_attr(mod_name, attr):
mod = find_cached_module(mod_name)
if mod is None:
return None
return getattr(mod, attr, None) | null |
177,630 | import sys
def find_class_name(val):
class_name = str(val.__class__)
if class_name.find('.') != -1:
class_name = class_name.split('.')[-1]
elif class_name.find("'") != -1: #does not have '.' (could be something like <type 'int'>)
class_name = class_name[class_name.index("'") + 1:]
if class_name.endswith("'>"):
class_name = class_name[:-2]
return class_name | null |
177,631 | import sys
from _pydevd_bundle.pydevd_constants import PANDAS_MAX_ROWS, PANDAS_MAX_COLS, PANDAS_MAX_COLWIDTH
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider
from _pydevd_bundle.pydevd_resolver import inspect, MethodWrapperType
from _pydevd_bundle.pydevd_utils import Timer
from .pydevd_helpers import find_mod_attr
from contextlib import contextmanager
try:
import inspect
except:
inspect = InspectStub()
class Timer(object):
def __init__(self, min_diff=PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT):
def print_time(self, msg='Elapsed:'):
def _report_slow(self, compute_msg, *args):
def report_if_compute_repr_attr_slow(self, attrs_tab_separated, attr_name, attr_type):
def _compute_repr_slow(self, diff, attrs_tab_separated, attr_name, attr_type):
def report_if_getting_attr_slow(self, cls, attr_name):
def _compute_get_attr_slow(self, diff, cls, attr_name):
def _get_dictionary(obj, replacements):
ret = dict()
cls = obj.__class__
for attr_name in dir(obj):
# This is interesting but it actually hides too much info from the dataframe.
# attr_type_in_cls = type(getattr(cls, attr_name, None))
# if attr_type_in_cls == property:
# ret[attr_name] = '<property (not computed)>'
# continue
timer = Timer()
try:
replacement = replacements.get(attr_name)
if replacement is not None:
ret[attr_name] = replacement
continue
attr_value = getattr(obj, attr_name, '<unable to get>')
if inspect.isroutine(attr_value) or isinstance(attr_value, MethodWrapperType):
continue
ret[attr_name] = attr_value
except Exception as e:
ret[attr_name] = '<error getting: %s>' % (e,)
finally:
timer.report_if_getting_attr_slow(cls, attr_name)
return ret | null |
177,632 | import sys
from _pydevd_bundle.pydevd_constants import PANDAS_MAX_ROWS, PANDAS_MAX_COLS, PANDAS_MAX_COLWIDTH
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider
from _pydevd_bundle.pydevd_resolver import inspect, MethodWrapperType
from _pydevd_bundle.pydevd_utils import Timer
from .pydevd_helpers import find_mod_attr
from contextlib import contextmanager
PANDAS_MAX_ROWS = as_int_in_env('PYDEVD_PANDAS_MAX_ROWS', 60)
PANDAS_MAX_COLS = as_int_in_env('PYDEVD_PANDAS_MAX_COLS', 10)
PANDAS_MAX_COLWIDTH = as_int_in_env('PYDEVD_PANDAS_MAX_COLWIDTH', 50)
def customize_pandas_options():
# The default repr depends on the settings of:
#
# pandas.set_option('display.max_columns', None)
# pandas.set_option('display.max_rows', None)
#
# which can make the repr **very** slow on some cases, so, we customize pandas to have
# smaller values if the current values are too big.
custom_options = []
from pandas import get_option
max_rows = get_option("display.max_rows")
max_cols = get_option("display.max_columns")
max_colwidth = get_option("display.max_colwidth")
if max_rows is None or max_rows > PANDAS_MAX_ROWS:
custom_options.append("display.max_rows")
custom_options.append(PANDAS_MAX_ROWS)
if max_cols is None or max_cols > PANDAS_MAX_COLS:
custom_options.append("display.max_columns")
custom_options.append(PANDAS_MAX_COLS)
if max_colwidth is None or max_colwidth > PANDAS_MAX_COLWIDTH:
custom_options.append("display.max_colwidth")
custom_options.append(PANDAS_MAX_COLWIDTH)
if custom_options:
from pandas import option_context
with option_context(*custom_options):
yield
else:
yield | null |
177,633 | from _pydev_bundle._pydev_saved_modules import thread, _code
from _pydevd_bundle.pydevd_constants import IS_JYTHON
from _pydevd_bundle.pydevconsole_code import InteractiveConsole
import os
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE
import traceback
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_save_locals
from _pydev_bundle.pydev_imports import Exec, _queue
import builtins as __builtin__
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_console_utils import CodeFragment
from _pydev_bundle.pydev_umd import runfile, _set_globals_function
class _ProcessExecQueueHelper:
_debug_hook = None
_return_control_osc = False
def set_debug_hook(debug_hook):
_ProcessExecQueueHelper._debug_hook = debug_hook | null |
177,634 | from _pydev_bundle._pydev_saved_modules import thread, _code
from _pydevd_bundle.pydevd_constants import IS_JYTHON
start_new_thread = thread.start_new_thread
from _pydevd_bundle.pydevconsole_code import InteractiveConsole
import os
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE
import traceback
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_save_locals
from _pydev_bundle.pydev_imports import Exec, _queue
import builtins as __builtin__
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_console_utils import CodeFragment
from _pydev_bundle.pydev_umd import runfile, _set_globals_function
if sys.version_info[0] >= 3:
__builtin__.runfile = runfile
else:
__builtin__.runfile = runfile
class InterpreterInterface(BaseInterpreterInterface):
'''
The methods in this class should be registered in the xml-rpc server.
'''
def __init__(self, host, client_port, mainThread, connect_status_queue=None):
BaseInterpreterInterface.__init__(self, mainThread, connect_status_queue)
self.client_port = client_port
self.host = host
self.namespace = {}
self.interpreter = InteractiveConsole(self.namespace)
self._input_error_printed = False
def do_add_exec(self, codeFragment):
command = Command(self.interpreter, codeFragment)
command.run()
return command.more
def get_namespace(self):
return self.namespace
def getCompletions(self, text, act_tok):
try:
from _pydev_bundle._pydev_completer import Completer
completer = Completer(self.namespace, None)
return completer.complete(act_tok)
except:
pydev_log.exception()
return []
def close(self):
sys.exit(0)
def get_greeting_msg(self):
return 'PyDev console: starting.\n'
if sys.platform != 'win32':
if not hasattr(os, 'kill'): # Jython may not have it.
else:
else:
def process_exec_queue(interpreter):
init_mpl_in_console(interpreter)
from pydev_ipython.inputhook import get_inputhook
try:
kill_if_pid_not_alive = int(os.environ.get('PYDEV_ECLIPSE_PID', '-1'))
except:
kill_if_pid_not_alive = -1
while 1:
if kill_if_pid_not_alive != -1:
if not pid_exists(kill_if_pid_not_alive):
exit()
# Running the request may have changed the inputhook in use
inputhook = get_inputhook()
if _ProcessExecQueueHelper._debug_hook:
_ProcessExecQueueHelper._debug_hook()
if inputhook:
try:
# Note: it'll block here until return_control returns True.
inputhook()
except:
pydev_log.exception()
try:
try:
code_fragment = interpreter.exec_queue.get(block=True, timeout=1 / 20.) # 20 calls/second
except _queue.Empty:
continue
if callable(code_fragment):
# It can be a callable (i.e.: something that must run in the main
# thread can be put in the queue for later execution).
code_fragment()
else:
more = interpreter.add_exec(code_fragment)
except KeyboardInterrupt:
interpreter.buffer = None
continue
except SystemExit:
raise
except:
pydev_log.exception('Error processing queue on pydevconsole.')
exit()
def do_exit(*args):
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) == 1:
os._exit(args[0])
else:
os._exit(0)
def start_console_server(host, port, interpreter):
try:
if port == 0:
host = ''
# I.e.: supporting the internal Jython version in PyDev to create a Jython interactive console inside Eclipse.
from _pydev_bundle.pydev_imports import SimpleXMLRPCServer as XMLRPCServer # @Reimport
try:
server = XMLRPCServer((host, port), logRequests=False, allow_none=True)
except:
sys.stderr.write('Error starting server with host: "%s", port: "%s", client_port: "%s"\n' % (host, port, interpreter.client_port))
sys.stderr.flush()
raise
# Tell UMD the proper default namespace
_set_globals_function(interpreter.get_namespace)
server.register_function(interpreter.execLine)
server.register_function(interpreter.execMultipleLines)
server.register_function(interpreter.getCompletions)
server.register_function(interpreter.getFrame)
server.register_function(interpreter.getVariable)
server.register_function(interpreter.changeVariable)
server.register_function(interpreter.getDescription)
server.register_function(interpreter.close)
server.register_function(interpreter.interrupt)
server.register_function(interpreter.handshake)
server.register_function(interpreter.connectToDebugger)
server.register_function(interpreter.hello)
server.register_function(interpreter.getArray)
server.register_function(interpreter.evaluate)
server.register_function(interpreter.ShowConsole)
server.register_function(interpreter.loadFullValue)
# Functions for GUI main loop integration
server.register_function(interpreter.enableGui)
if port == 0:
(h, port) = server.socket.getsockname()
print(port)
print(interpreter.client_port)
while True:
try:
server.serve_forever()
except:
# Ugly code to be py2/3 compatible
# https://sw-brainwy.rhcloud.com/tracker/PyDev/534:
# Unhandled "interrupted system call" error in the pydevconsol.py
e = sys.exc_info()[1]
retry = False
try:
retry = e.args[0] == 4 # errno.EINTR
except:
pass
if not retry:
raise
# Otherwise, keep on going
return server
except:
pydev_log.exception()
# Notify about error to avoid long waiting
connection_queue = interpreter.get_connect_status_queue()
if connection_queue is not None:
connection_queue.put(False)
class InterpreterInterface(BaseInterpreterInterface):
'''
The methods in this class should be registered in the xml-rpc server.
'''
def __init__(self, host, client_port, main_thread, show_banner=True, connect_status_queue=None):
BaseInterpreterInterface.__init__(self, main_thread, connect_status_queue)
self.client_port = client_port
self.host = host
self.interpreter = get_pydev_frontend(host, client_port)
self._input_error_printed = False
self.notification_succeeded = False
self.notification_tries = 0
self.notification_max_tries = 3
self.show_banner = show_banner
self.notify_about_magic()
def get_greeting_msg(self):
if self.show_banner:
self.interpreter.show_banner()
return self.interpreter.get_greeting_msg()
def do_add_exec(self, code_fragment):
self.notify_about_magic()
if code_fragment.text.rstrip().endswith('??'):
print('IPython-->')
try:
res = bool(self.interpreter.add_exec(code_fragment.text))
finally:
if code_fragment.text.rstrip().endswith('??'):
print('<--IPython')
return res
def get_namespace(self):
return self.interpreter.get_namespace()
def getCompletions(self, text, act_tok):
return self.interpreter.getCompletions(text, act_tok)
def close(self):
sys.exit(0)
def notify_about_magic(self):
if not self.notification_succeeded:
self.notification_tries += 1
if self.notification_tries > self.notification_max_tries:
return
completions = self.getCompletions("%", "%")
magic_commands = [x[0] for x in completions]
server = self.get_server()
if server is not None:
try:
server.NotifyAboutMagic(magic_commands, self.interpreter.is_automagic())
self.notification_succeeded = True
except:
self.notification_succeeded = False
def get_ipython_hidden_vars_dict(self):
try:
if hasattr(self.interpreter, 'ipython') and hasattr(self.interpreter.ipython, 'user_ns_hidden'):
user_ns_hidden = self.interpreter.ipython.user_ns_hidden
if isinstance(user_ns_hidden, dict):
# Since IPython 2 dict `user_ns_hidden` contains hidden variables and values
user_hidden_dict = user_ns_hidden.copy()
else:
# In IPython 1.x `user_ns_hidden` used to be a set with names of hidden variables
user_hidden_dict = dict([(key, val) for key, val in self.interpreter.ipython.user_ns.items()
if key in user_ns_hidden])
# while `_`, `__` and `___` were not initialized, they are not presented in `user_ns_hidden`
user_hidden_dict.setdefault('_', '')
user_hidden_dict.setdefault('__', '')
user_hidden_dict.setdefault('___', '')
return user_hidden_dict
except:
# Getting IPython variables shouldn't break loading frame variables
traceback.print_exc()
def start_server(host, port, client_port):
# replace exit (see comments on method)
# note that this does not work in jython!!! (sys method can't be replaced).
sys.exit = do_exit
interpreter = InterpreterInterface(host, client_port, threading.current_thread())
start_new_thread(start_console_server, (host, port, interpreter))
process_exec_queue(interpreter) | null |
177,635 | from _pydev_bundle._pydev_saved_modules import thread, _code
from _pydevd_bundle.pydevd_constants import IS_JYTHON
from _pydevd_bundle.pydevconsole_code import InteractiveConsole
import os
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE
import traceback
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_save_locals
from _pydev_bundle.pydev_imports import Exec, _queue
import builtins as __builtin__
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_console_utils import CodeFragment
from _pydev_bundle.pydev_umd import runfile, _set_globals_function
def get_interpreter():
def get_ipython_hidden_vars():
if IPYTHON and hasattr(__builtin__, 'interpreter'):
interpreter = get_interpreter()
return interpreter.get_ipython_hidden_vars_dict() | null |
177,636 | from _pydev_bundle._pydev_saved_modules import thread, _code
from _pydevd_bundle.pydevd_constants import IS_JYTHON
from _pydevd_bundle.pydevconsole_code import InteractiveConsole
import os
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE
import traceback
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_save_locals
from _pydev_bundle.pydev_imports import Exec, _queue
import builtins as __builtin__
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_console_utils import CodeFragment
from _pydev_bundle.pydev_umd import runfile, _set_globals_function
def get_interpreter():
try:
interpreterInterface = getattr(__builtin__, 'interpreter')
except AttributeError:
interpreterInterface = InterpreterInterface(None, None, threading.current_thread())
__builtin__.interpreter = interpreterInterface
sys.stderr.write(interpreterInterface.get_greeting_msg())
sys.stderr.flush()
return interpreterInterface
def get_completions(text, token, globals, locals):
interpreterInterface = get_interpreter()
interpreterInterface.interpreter.update(globals, locals)
return interpreterInterface.getCompletions(text, token) | null |
177,637 | from _pydev_bundle._pydev_saved_modules import thread, _code
from _pydevd_bundle.pydevd_constants import IS_JYTHON
from _pydevd_bundle.pydevconsole_code import InteractiveConsole
compile_command = _code.compile_command
import os
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE
import traceback
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_save_locals
from _pydev_bundle.pydev_imports import Exec, _queue
import builtins as __builtin__
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_console_utils import CodeFragment
from _pydev_bundle.pydev_umd import runfile, _set_globals_function
def exec_code(code, globals, locals, debugger):
interpreterInterface = get_interpreter()
interpreterInterface.interpreter.update(globals, locals)
res = interpreterInterface.need_more(code)
if res:
return True
interpreterInterface.add_exec(code, debugger)
return False
class ConsoleWriter(InteractiveInterpreter):
skip = 0
def __init__(self, locals=None):
InteractiveInterpreter.__init__(self, locals)
def write(self, data):
# if (data.find("global_vars") == -1 and data.find("pydevd") == -1):
if self.skip > 0:
self.skip -= 1
else:
if data == "Traceback (most recent call last):\n":
self.skip = 1
sys.stderr.write(data)
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred."""
# Override for avoid using sys.excepthook PY-12600
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
if filename and type is SyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename, lineno, offset, line) = value.args
except ValueError:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
value = SyntaxError(msg, (filename, lineno, offset, line))
sys.last_value = value
list = traceback.format_exception_only(type, value)
sys.stderr.write(''.join(list))
def showtraceback(self, *args, **kwargs):
"""Display the exception that just occurred."""
# Override for avoid using sys.excepthook PY-12600
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
lines = traceback.format_list(tblist)
if lines:
lines.insert(0, "Traceback (most recent call last):\n")
lines.extend(traceback.format_exception_only(type, value))
finally:
tblist = tb = None
sys.stderr.write(''.join(lines))
class CodeFragment:
def __init__(self, text, is_single_line=True):
self.text = text
self.is_single_line = is_single_line
def append(self, code_fragment):
self.text = self.text + "\n" + code_fragment.text
if not code_fragment.is_single_line:
self.is_single_line = False
The provided code snippet includes necessary dependencies for implementing the `console_exec` function. Write a Python function `def console_exec(thread_id, frame_id, expression, dbg)` to solve the following problem:
returns 'False' in case expression is partially correct
Here is the function:
def console_exec(thread_id, frame_id, expression, dbg):
"""returns 'False' in case expression is partially correct
"""
frame = dbg.find_frame(thread_id, frame_id)
is_multiline = expression.count('@LINE@') > 1
expression = str(expression.replace('@LINE@', '\n'))
# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
# (Names not resolved in generator expression in method)
# See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals
if IPYTHON:
need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg)
if not need_more:
pydevd_save_locals.save_locals(frame)
return need_more
interpreter = ConsoleWriter()
if not is_multiline:
try:
code = compile_command(expression)
except (OverflowError, SyntaxError, ValueError):
# Case 1
interpreter.showsyntaxerror()
return False
if code is None:
# Case 2
return True
else:
code = expression
# Case 3
try:
Exec(code, updated_globals, frame.f_locals)
except SystemExit:
raise
except:
interpreter.showtraceback()
else:
pydevd_save_locals.save_locals(frame)
return False | returns 'False' in case expression is partially correct |
177,638 | import os
import sys
import traceback
from pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console
from _pydev_bundle._pydev_saved_modules import threading, _queue
from _pydev_bundle import pydev_imports
from _pydevd_bundle.pydevd_utils import save_main_module
from _pydev_bundle.pydev_console_utils import StdIn
from pydevd_file_utils import get_fullname
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DeprecationWarning)
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
m.__loader__ = getattr(sys.modules[module_name], '__loader__')
m.__file__ = file
return m
def get_fullname(mod_name):
import pkgutil
try:
loader = pkgutil.get_loader(mod_name)
except:
return None
if loader is not None:
for attr in ("get_filename", "_get_filename"):
meth = getattr(loader, attr, None)
if meth is not None:
return meth(mod_name)
return None
def run_file(file, globals=None, locals=None, is_module=False):
module_name = None
entry_point_fn = None
if is_module:
file, _, entry_point_fn = file.partition(':')
module_name = file
filename = get_fullname(file)
if filename is None:
sys.stderr.write("No module named %s\n" % file)
return
else:
file = filename
if os.path.isdir(file):
new_target = os.path.join(file, '__main__.py')
if os.path.isfile(new_target):
file = new_target
if globals is None:
m = save_main_module(file, 'pydev_run_in_console')
globals = m.__dict__
try:
globals['__builtins__'] = __builtins__
except NameError:
pass # Not there on Jython...
if locals is None:
locals = globals
if not is_module:
sys.path.insert(0, os.path.split(file)[0])
print('Running %s' % file)
try:
if not is_module:
pydev_imports.execfile(file, globals, locals) # execute the script
else:
# treat ':' as a seperator between module and entry point function
# if there is no entry point we run we same as with -m switch. Otherwise we perform
# an import and execute the entry point
if entry_point_fn:
mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals)
func = getattr(mod, entry_point_fn)
func()
else:
# Run with the -m switch
from _pydevd_bundle import pydevd_runpy
pydevd_runpy._run_module_as_main(module_name)
except:
traceback.print_exc()
return globals | null |
177,639 | import os
import sys
import traceback
from pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console
from _pydev_bundle._pydev_saved_modules import threading, _queue
from _pydev_bundle import pydev_imports
from _pydevd_bundle.pydevd_utils import save_main_module
from _pydev_bundle.pydev_console_utils import StdIn
from pydevd_file_utils import get_fullname
The provided code snippet includes necessary dependencies for implementing the `skip_successful_exit` function. Write a Python function `def skip_successful_exit(*args)` to solve the following problem:
System exit in file shouldn't kill interpreter (i.e. in `timeit`)
Here is the function:
def skip_successful_exit(*args):
""" System exit in file shouldn't kill interpreter (i.e. in `timeit`)"""
if len(args) == 1 and args[0] in (0, None):
pass
else:
raise SystemExit(*args) | System exit in file shouldn't kill interpreter (i.e. in `timeit`) |
177,640 | import os
import sys
import traceback
from pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console
from _pydev_bundle._pydev_saved_modules import threading, _queue
from _pydev_bundle import pydev_imports
from _pydevd_bundle.pydevd_utils import save_main_module
from _pydev_bundle.pydev_console_utils import StdIn
from pydevd_file_utils import get_fullname
def process_args(argv):
setup_args = {'file': '', 'module': False}
setup_args['port'] = argv[1]
del argv[1]
setup_args['client_port'] = argv[1]
del argv[1]
module_flag = "--module"
if module_flag in argv:
i = argv.index(module_flag)
if i != -1:
setup_args['module'] = True
setup_args['file'] = argv[i + 1]
del sys.argv[i]
else:
setup_args['file'] = argv[1]
del argv[0]
return setup_args | null |
177,641 | import os
import sys
from setuptools import setup
extension_folder, target_pydevd_name, target_frame_eval, force_cython = process_args()
if target_pydevd_name is None:
target_pydevd_name = extension_name
if extension_folder:
os.chdir(extension_folder)
for folder in [file for file in os.listdir(extension_folder) if
file != 'build' and os.path.isdir(os.path.join(extension_folder, file))]:
file = os.path.join(folder, "__init__.py")
if not os.path.exists(file):
open(file, 'a').close()
def process_args():
extension_folder = None
target_pydevd_name = None
target_frame_eval = None
force_cython = False
for i, arg in enumerate(sys.argv[:]):
if arg == '--build-lib':
extension_folder = sys.argv[i + 1]
# It shouldn't be removed from sys.argv (among with --build-temp) because they're passed further to setup()
if arg.startswith('--target-pyd-name='):
sys.argv.remove(arg)
target_pydevd_name = arg[len('--target-pyd-name='):]
if arg.startswith('--target-pyd-frame-eval='):
sys.argv.remove(arg)
target_frame_eval = arg[len('--target-pyd-frame-eval='):]
if arg == '--force-cython':
sys.argv.remove(arg)
force_cython = True
return extension_folder, target_pydevd_name, target_frame_eval, force_cython | null |
177,642 | import os
import sys
from setuptools import setup
os.chdir(os.path.dirname(os.path.abspath(__file__)))
def process_template_file(contents):
def setup(**attrs):
setup.__doc__ = distutils.core.setup.__doc__
class Extension(old_Extension):
def __init__(
self, name, sources,
include_dirs=None,
define_macros=None,
undef_macros=None,
library_dirs=None,
libraries=None,
runtime_library_dirs=None,
extra_objects=None,
extra_compile_args=None,
extra_link_args=None,
export_symbols=None,
swig_opts=None,
depends=None,
language=None,
f2py_options=None,
module_dirs=None,
extra_c_compile_args=None,
extra_cxx_compile_args=None,
extra_f77_compile_args=None,
extra_f90_compile_args=None,):
def has_cxx_sources(self):
def has_f2py_sources(self):
def build_extension(dir_name, extension_name, target_pydevd_name, force_cython, extended=False, has_pxd=False, template=False):
pyx_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pyx" % (extension_name,))
if template:
pyx_template_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.template.pyx" % (extension_name,))
with open(pyx_template_file, 'r') as stream:
contents = stream.read()
contents = process_template_file(contents)
with open(pyx_file, 'w') as stream:
stream.write(contents)
if target_pydevd_name != extension_name:
# It MUST be there in this case!
# (otherwise we'll have unresolved externals because the .c file had another name initially).
import shutil
# We must force cython in this case (but only in this case -- for the regular setup in the user machine, we
# should always compile the .c file).
force_cython = True
new_pyx_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pyx" % (target_pydevd_name,))
new_c_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.c" % (target_pydevd_name,))
shutil.copy(pyx_file, new_pyx_file)
pyx_file = new_pyx_file
if has_pxd:
pxd_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pxd" % (extension_name,))
new_pxd_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pxd" % (target_pydevd_name,))
shutil.copy(pxd_file, new_pxd_file)
assert os.path.exists(pyx_file)
try:
c_files = [os.path.join(dir_name, "%s.c" % target_pydevd_name), ]
if force_cython:
for c_file in c_files:
try:
os.remove(c_file)
except:
pass
from Cython.Build import cythonize # @UnusedImport
# Generate the .c files in cythonize (will not compile at this point).
target = "%s/%s.pyx" % (dir_name, target_pydevd_name,)
cythonize([target])
# Workarounds needed in CPython 3.8 and 3.9 to access PyInterpreterState.eval_frame.
for c_file in c_files:
with open(c_file, 'r') as stream:
c_file_contents = stream.read()
if '#include "internal/pycore_gc.h"' not in c_file_contents:
c_file_contents = c_file_contents.replace('#include "Python.h"', '''#include "Python.h"
#if PY_VERSION_HEX >= 0x03090000
#include "internal/pycore_gc.h"
#include "internal/pycore_interp.h"
#endif
''')
if '#include "internal/pycore_pystate.h"' not in c_file_contents:
c_file_contents = c_file_contents.replace('#include "pystate.h"', '''#include "pystate.h"
#if PY_VERSION_HEX >= 0x03080000
#include "internal/pycore_pystate.h"
#endif
''')
# We want the same output on Windows and Linux.
c_file_contents = c_file_contents.replace('\r\n', '\n').replace('\r', '\n')
c_file_contents = c_file_contents.replace(r'_pydevd_frame_eval\\release_mem.h', '_pydevd_frame_eval/release_mem.h')
c_file_contents = c_file_contents.replace(r'_pydevd_frame_eval\\pydevd_frame_evaluator.pyx', '_pydevd_frame_eval/pydevd_frame_evaluator.pyx')
c_file_contents = c_file_contents.replace(r'_pydevd_bundle\\pydevd_cython.pxd', '_pydevd_bundle/pydevd_cython.pxd')
c_file_contents = c_file_contents.replace(r'_pydevd_bundle\\pydevd_cython.pyx', '_pydevd_bundle/pydevd_cython.pyx')
with open(c_file, 'w') as stream:
stream.write(c_file_contents)
# Always compile the .c (and not the .pyx) file (which we should keep up-to-date by running build_tools/build.py).
from distutils.extension import Extension
extra_compile_args = []
extra_link_args = []
if 'linux' in sys.platform:
# Enabling -flto brings executable from 4MB to 0.56MB and -Os to 0.41MB
# Profiling shows an execution around 3-5% slower with -Os vs -O3,
# so, kept only -flto.
extra_compile_args = ["-flto", "-O3"]
extra_link_args = extra_compile_args[:]
# Note: also experimented with profile-guided optimization. The executable
# size became a bit smaller (from 0.56MB to 0.5MB) but this would add an
# extra step to run the debugger to obtain the optimizations
# so, skipped it for now (note: the actual benchmarks time was in the
# margin of a 0-1% improvement, which is probably not worth it for
# speed increments).
# extra_compile_args = ["-flto", "-fprofile-generate"]
# ... Run benchmarks ...
# extra_compile_args = ["-flto", "-fprofile-use", "-fprofile-correction"]
elif 'win32' in sys.platform:
pass
# uncomment to generate pdbs for visual studio.
# extra_compile_args=["-Zi", "/Od"]
# extra_link_args=["-debug"]
kwargs = {}
if extra_link_args:
kwargs['extra_link_args'] = extra_link_args
if extra_compile_args:
kwargs['extra_compile_args'] = extra_compile_args
ext_modules = [
Extension(
"%s%s.%s" % (dir_name, "_ext" if extended else "", target_pydevd_name,),
c_files,
**kwargs
)]
# This is needed in CPython 3.8 to be able to include internal/pycore_pystate.h
# (needed to set PyInterpreterState.eval_frame).
for module in ext_modules:
module.define_macros = [('Py_BUILD_CORE_MODULE', '1')]
setup(
name='Cythonize',
ext_modules=ext_modules
)
finally:
if target_pydevd_name != extension_name:
try:
os.remove(new_pyx_file)
except:
import traceback
traceback.print_exc()
try:
os.remove(new_c_file)
except:
import traceback
traceback.print_exc()
if has_pxd:
try:
os.remove(new_pxd_file)
except:
import traceback
traceback.print_exc() | null |
177,643 | import sys
from functools import partial
from pydev_ipython.version import check_version
QT_API_PYQT = 'pyqt'
QT_API_PYQTv1 = 'pyqtv1'
QT_API_PYQT_DEFAULT = 'pyqtdefault'
QT_API_PYSIDE = 'pyside'
QT_API_PYSIDE2 = 'pyside2'
QT_API_PYQT5 = 'pyqt5'
def commit_api(api):
"""Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports"""
if api == QT_API_PYSIDE:
ID.forbid('PyQt4')
ID.forbid('PyQt5')
else:
ID.forbid('PySide')
ID.forbid('PySide2')
def loaded_api():
"""Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyside2', 'pyqt', or 'pyqtv1'
"""
if 'PyQt4.QtCore' in sys.modules:
if qtapi_version() == 2:
return QT_API_PYQT
else:
return QT_API_PYQTv1
elif 'PySide.QtCore' in sys.modules:
return QT_API_PYSIDE
elif 'PySide2.QtCore' in sys.modules:
return QT_API_PYSIDE2
elif 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None
def has_binding(api):
"""Safely check for PyQt4 or PySide, without importing
submodules
Parameters
----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault']
Which module to check for
Returns
-------
True if the relevant module appears to be importable
"""
# we can't import an incomplete pyside and pyqt4
# this will cause a crash in sip (#1431)
# check for complete presence before importing
module_name = {QT_API_PYSIDE: 'PySide',
QT_API_PYSIDE2: 'PySide2',
QT_API_PYQT: 'PyQt4',
QT_API_PYQTv1: 'PyQt4',
QT_API_PYQT_DEFAULT: 'PyQt4',
QT_API_PYQT5: 'PyQt5',
}
module_name = module_name[api]
import imp
try:
# importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
# ...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
# we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ImportError:
return False
def can_import(api):
"""Safely query whether an API is importable, without importing it"""
if not has_binding(api):
return False
current = loaded_api()
if api == QT_API_PYQT_DEFAULT:
return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None]
else:
return current in [api, None]
def import_pyqt4(version=2):
"""
Import PyQt4
Parameters
----------
version : 1, 2, or None
Which QString/QVariant API to use. Set to None to use the system
default
ImportErrors raised within this function are non-recoverable
"""
# The new-style string API (version=2) automatically
# converts QStrings to Unicode Python strings. Also, automatically unpacks
# QVariants to their underlying objects.
import sip
if version is not None:
sip.setapi('QString', version)
sip.setapi('QVariant', version)
from PyQt4 import QtGui, QtCore, QtSvg
if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
QtCore.PYQT_VERSION_STR)
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
# query for the API version (in case version == None)
version = sip.getapi('QString')
api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
return QtCore, QtGui, QtSvg, api
def import_pyqt5():
"""
Import PyQt5
ImportErrors raised within this function are non-recoverable
"""
from PyQt5 import QtGui, QtCore, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
return QtCore, QtGui, QtSvg, QT_API_PYQT5
def import_pyside():
"""
Import PySide
ImportErrors raised within this function are non-recoverable
"""
from PySide import QtGui, QtCore, QtSvg # @UnresolvedImport
return QtCore, QtGui, QtSvg, QT_API_PYSIDE
def import_pyside2():
"""
Import PySide2
ImportErrors raised within this function are non-recoverable
"""
from PySide2 import QtGui, QtCore, QtSvg # @UnresolvedImport
return QtCore, QtGui, QtSvg, QT_API_PYSIDE
class partial(Generic[_T]):
func: Callable[..., _T]
args: Tuple[Any, ...]
keywords: Dict[str, Any]
def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ...
def __call__(self, *args: Any, **kwargs: Any) -> _T: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
The provided code snippet includes necessary dependencies for implementing the `load_qt` function. Write a Python function `def load_qt(api_options)` to solve the following problem:
Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options: List of strings The order of APIs to try. Valid items are 'pyside', 'pyqt', and 'pyqtv1' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either becaues they aren't installed, or because an incompatible library has already been installed)
Here is the function:
def load_qt(api_options):
"""
Attempt to import Qt, given a preference list
of permissible bindings
It is safe to call this function multiple times.
Parameters
----------
api_options: List of strings
The order of APIs to try. Valid items are 'pyside',
'pyqt', and 'pyqtv1'
Returns
-------
A tuple of QtCore, QtGui, QtSvg, QT_API
The first three are the Qt modules. The last is the
string indicating which module was loaded.
Raises
------
ImportError, if it isn't possible to import any requested
bindings (either becaues they aren't installed, or because
an incompatible library has already been installed)
"""
loaders = {QT_API_PYSIDE: import_pyside,
QT_API_PYSIDE2: import_pyside2,
QT_API_PYQT: import_pyqt4,
QT_API_PYQTv1: partial(import_pyqt4, version=1),
QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None),
QT_API_PYQT5: import_pyqt5,
}
for api in api_options:
if api not in loaders:
raise RuntimeError(
"Invalid Qt API %r, valid values are: %r, %r, %r, %r, %r, %r" %
(api, QT_API_PYSIDE, QT_API_PYSIDE, QT_API_PYQT,
QT_API_PYQTv1, QT_API_PYQT_DEFAULT, QT_API_PYQT5))
if not can_import(api):
continue
# cannot safely recover from an ImportError during this
result = loaders[api]()
api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
commit_api(api)
return result
else:
raise ImportError("""
Could not load requested Qt binding. Please ensure that
PyQt4 >= 4.7 or PySide >= 1.0.3 is available,
and only one is imported per session.
Currently-imported Qt library: %r
PyQt4 installed: %s
PyQt5 installed: %s
PySide >= 1.0.3 installed: %s
PySide2 installed: %s
Tried to load: %r
""" % (loaded_api(),
has_binding(QT_API_PYQT),
has_binding(QT_API_PYQT5),
has_binding(QT_API_PYSIDE),
has_binding(QT_API_PYSIDE2),
api_options)) | Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options: List of strings The order of APIs to try. Valid items are 'pyside', 'pyqt', and 'pyqtv1' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either becaues they aren't installed, or because an incompatible library has already been installed) |
177,644 | import os
import sys
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import pyglet
from pydev_ipython.inputhook import stdin_ready
if sys.platform.startswith('linux'):
def flip(window):
try:
window.flip()
except AttributeError:
pass
else:
def flip(window):
window.flip()
stdin_ready = inputhook_manager.return_control
The provided code snippet includes necessary dependencies for implementing the `inputhook_pyglet` function. Write a Python function `def inputhook_pyglet()` to solve the following problem:
Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
Here is the function:
def inputhook_pyglet():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
try:
t = clock()
while not stdin_ready():
pyglet.clock.tick()
for window in pyglet.app.windows:
window.switch_to()
window.dispatch_events()
window.dispatch_event('on_draw')
flip(window)
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0 | Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. |
177,645 | import sys
import signal
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import wx
from pydev_ipython.inputhook import stdin_ready
The provided code snippet includes necessary dependencies for implementing the `inputhook_wx1` function. Write a Python function `def inputhook_wx1()` to solve the following problem:
Run the wx event loop by processing pending events only. This approach seems to work, but its performance is not great as it relies on having PyOS_InputHook called regularly.
Here is the function:
def inputhook_wx1():
"""Run the wx event loop by processing pending events only.
This approach seems to work, but its performance is not great as it
relies on having PyOS_InputHook called regularly.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
# Make a temporary event loop and process system events until
# there are no more waiting, then allow idle events (which
# will also deal with pending or posted wx events.)
evtloop = wx.EventLoop() # @UndefinedVariable
ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable
while evtloop.Pending():
evtloop.Dispatch()
app.ProcessIdle()
del ea
except KeyboardInterrupt:
pass
return 0 | Run the wx event loop by processing pending events only. This approach seems to work, but its performance is not great as it relies on having PyOS_InputHook called regularly. |
177,646 | import sys
import signal
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import wx
from pydev_ipython.inputhook import stdin_ready
class EventLoopRunner(object):
def Run(self, time):
self.evtloop = wx.EventLoop() # @UndefinedVariable
self.timer = EventLoopTimer(self.check_stdin)
self.timer.Start(time)
self.evtloop.Run()
def check_stdin(self):
if stdin_ready():
self.timer.Stop()
self.evtloop.Exit()
The provided code snippet includes necessary dependencies for implementing the `inputhook_wx2` function. Write a Python function `def inputhook_wx2()` to solve the following problem:
Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often.
Here is the function:
def inputhook_wx2():
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
elr = EventLoopRunner()
# As this time is made shorter, keyboard response improves, but idle
# CPU load goes up. 10 ms seems like a good compromise.
elr.Run(time=10) # CHANGE time here to control polling interval
except KeyboardInterrupt:
pass
return 0 | Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. |
177,647 | import sys
import signal
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import wx
from pydev_ipython.inputhook import stdin_ready
stdin_ready = inputhook_manager.return_control
The provided code snippet includes necessary dependencies for implementing the `inputhook_wx3` function. Write a Python function `def inputhook_wx3()` to solve the following problem:
Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
Here is the function:
def inputhook_wx3():
"""Run the wx event loop by processing pending events only.
This is like inputhook_wx1, but it keeps processing pending events
until stdin is ready. After processing all pending events, a call to
time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
This sleep time should be tuned though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
if hasattr(wx, 'IsMainThread'):
assert wx.IsMainThread() # @UndefinedVariable
else:
assert wx.Thread_IsMain() # @UndefinedVariable
# The import of wx on Linux sets the handler for signal.SIGINT
# to 0. This is a bug in wx or gtk. We fix by just setting it
# back to the Python default.
if not callable(signal.getsignal(signal.SIGINT)):
signal.signal(signal.SIGINT, signal.default_int_handler)
evtloop = wx.EventLoop() # @UndefinedVariable
ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable
t = clock()
while not stdin_ready():
while evtloop.Pending():
t = clock()
evtloop.Dispatch()
app.ProcessIdle()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
del ea
except KeyboardInterrupt:
pass
return 0 | Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. |
177,648 | from pydev_ipython.inputhook import stdin_ready
TCL_DONT_WAIT = 1 << 1
stdin_ready = inputhook_manager.return_control
def create_inputhook_tk(app):
def inputhook_tk():
while app.dooneevent(TCL_DONT_WAIT) == 1:
if stdin_ready():
break
return 0
return inputhook_tk | null |
177,649 | import os
import signal
import threading
from pydev_ipython.qt_for_kernel import QtCore, QtGui
from pydev_ipython.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
class InteractiveShell:
_instance = None
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def set_hook(self, *args, **kwargs):
# We don't consider the pre_prompt_hook because we don't have
# KeyboardInterrupts to consider since we are running under PyDev
pass
got_kbdint = False
sigint_timer = None
def ignore_CTRL_C():
"""Ignore CTRL+C (not implemented)."""
pass
def allow_CTRL_C():
"""Take CTRL+C into account (not implemented)."""
pass
stdin_ready = inputhook_manager.return_control
The provided code snippet includes necessary dependencies for implementing the `create_inputhook_qt5` function. Write a Python function `def create_inputhook_qt5(mgr, app=None)` to solve the following problem:
Create an input hook for running the Qt5 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt5's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt.
Here is the function:
def create_inputhook_qt5(mgr, app=None):
"""Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt5's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt5'):
return app, ip._inputhook_qt5
# Otherwise create the inputhook_qt5/preprompthook_qt5 pair of
# hooks (they both share the got_kbdint flag)
def inputhook_qt5():
"""PyOS_InputHook python hook for Qt5.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
# Generally a program would run QCoreApplication::exec()
# from main() to enter and process the Qt event loop until
# quit() or exit() is called and the program terminates.
#
# For our input hook integration, we need to repeatedly
# enter and process the Qt event loop for only a short
# amount of time (say 50ms) to ensure that Python stays
# responsive to other user inputs.
#
# A naive approach would be to repeatedly call
# QCoreApplication::exec(), using a timer to quit after a
# short amount of time. Unfortunately, QCoreApplication
# emits an aboutToQuit signal before stopping, which has
# the undesirable effect of closing all modal windows.
#
# To work around this problem, we instead create a
# QEventLoop and call QEventLoop::exec(). Other than
# setting some state variables which do not seem to be
# used anywhere, the only thing QCoreApplication adds is
# the aboutToQuit signal which is precisely what we are
# trying to avoid.
timer = QtCore.QTimer()
event_loop = QtCore.QEventLoop()
timer.timeout.connect(event_loop.quit)
while not stdin_ready():
timer.start(50)
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
global got_kbdint, sigint_timer
ignore_CTRL_C()
got_kbdint = True
mgr.clear_inputhook()
# This generates a second SIGINT so the user doesn't have to
# press CTRL+C twice to get a clean prompt.
#
# Since we can't catch the resulting KeyboardInterrupt here
# (because this is a ctypes callback), we use a timer to
# generate the SIGINT after we leave this callback.
#
# Unfortunately this doesn't work on Windows (SIGINT kills
# Python and CTRL_C_EVENT doesn't work).
if(os.name == 'posix'):
pid = os.getpid()
if(not sigint_timer):
sigint_timer = threading.Timer(.01, os.kill,
args=[pid, signal.SIGINT])
sigint_timer.start()
else:
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt5, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt5(ishell):
"""'pre_prompt_hook' used to restore the Qt5 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
global got_kbdint, sigint_timer
if(sigint_timer):
sigint_timer.cancel()
sigint_timer = None
if got_kbdint:
mgr.set_inputhook(inputhook_qt5)
got_kbdint = False
ip._inputhook_qt5 = inputhook_qt5
ip.set_hook('pre_prompt_hook', preprompthook_qt5)
return app, inputhook_qt5 | Create an input hook for running the Qt5 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt5's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt. |
177,650 | import os
import sys
from _pydev_bundle._pydev_saved_modules import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
from pydev_ipython.inputhook import stdin_ready
def glut_display():
# Dummy display function
pass | null |
177,651 | import os
import sys
from _pydev_bundle._pydev_saved_modules import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
from pydev_ipython.inputhook import stdin_ready
def glut_idle():
# Dummy idle function
pass | null |
177,652 | import os
import sys
from _pydev_bundle._pydev_saved_modules import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
from pydev_ipython.inputhook import stdin_ready
glutMainLoopEvent = None
def glut_close():
# Close function only hides the current window
glut.glutHideWindow()
glutMainLoopEvent() | null |
177,653 | import os
import sys
from _pydev_bundle._pydev_saved_modules import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
from pydev_ipython.inputhook import stdin_ready
glutMainLoopEvent = None
def glut_int_handler(signum, frame):
# Catch sigint and print the defautl message
signal.signal(signal.SIGINT, signal.default_int_handler)
print('\nKeyboardInterrupt')
# Need to reprint the prompt at this stage
stdin_ready = inputhook_manager.return_control
The provided code snippet includes necessary dependencies for implementing the `inputhook_glut` function. Write a Python function `def inputhook_glut()` to solve the following problem:
Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
Here is the function:
def inputhook_glut():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
signal.signal(signal.SIGINT, glut_int_handler)
try:
t = clock()
# Make sure the default window is set after a window has been closed
if glut.glutGetWindow() == 0:
glut.glutSetWindow(1)
glutMainLoopEvent()
return 0
while not stdin_ready():
glutMainLoopEvent()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0 | Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. |
177,654 | import os
import sys
from pydev_ipython.version import check_version
from pydev_ipython.qt_loaders import (load_qt, QT_API_PYSIDE, QT_API_PYSIDE2,
QT_API_PYQT, QT_API_PYQT_DEFAULT,
loaded_api, QT_API_PYQT5)
def matplotlib_options(mpl):
if mpl is None:
return
# #PyDev-779: In pysrc/pydev_ipython/qt_for_kernel.py, matplotlib_options should be replaced with latest from ipython
# (i.e.: properly check backend to decide upon qt4/qt5).
backend = mpl.rcParams.get('backend', None)
if backend == 'Qt4Agg':
mpqt = mpl.rcParams.get('backend.qt4', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyside':
return [QT_API_PYSIDE]
elif mpqt.lower() == 'pyqt4':
return [QT_API_PYQT_DEFAULT]
elif mpqt.lower() == 'pyqt4v2':
return [QT_API_PYQT]
raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" %
mpqt)
elif backend == 'Qt5Agg':
mpqt = mpl.rcParams.get('backend.qt5', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyqt5':
return [QT_API_PYQT5]
raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" %
mpqt)
# Fallback without checking backend (previous code)
mpqt = mpl.rcParams.get('backend.qt4', None)
if mpqt is None:
mpqt = mpl.rcParams.get('backend.qt5', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyside':
return [QT_API_PYSIDE]
elif mpqt.lower() == 'pyqt4':
return [QT_API_PYQT_DEFAULT]
elif mpqt.lower() == 'pyqt5':
return [QT_API_PYQT5]
raise ImportError("unhandled value for qt backend from matplotlib: %r" %
mpqt)
def check_version(v, check):
"""check version string v >= check
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their own packages up to date.
"""
try:
return LooseVersion(v) >= LooseVersion(check)
except TypeError:
return True
QT_API_PYQT_DEFAULT = 'pyqtdefault'
QT_API_PYSIDE = 'pyside'
QT_API_PYSIDE2 = 'pyside2'
QT_API_PYQT5 = 'pyqt5'
def loaded_api():
"""Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyside2', 'pyqt', or 'pyqtv1'
"""
if 'PyQt4.QtCore' in sys.modules:
if qtapi_version() == 2:
return QT_API_PYQT
else:
return QT_API_PYQTv1
elif 'PySide.QtCore' in sys.modules:
return QT_API_PYSIDE
elif 'PySide2.QtCore' in sys.modules:
return QT_API_PYSIDE2
elif 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None
The provided code snippet includes necessary dependencies for implementing the `get_options` function. Write a Python function `def get_options()` to solve the following problem:
Return a list of acceptable QT APIs, in decreasing order of preference
Here is the function:
def get_options():
"""Return a list of acceptable QT APIs, in decreasing order of
preference
"""
# already imported Qt somewhere. Use that
loaded = loaded_api()
if loaded is not None:
return [loaded]
mpl = sys.modules.get('matplotlib', None)
if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
# 1.0.1 only supports PyQt4 v1
return [QT_API_PYQT_DEFAULT]
if os.environ.get('QT_API', None) is None:
# no ETS variable. Ask mpl, then use either
return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT5]
# ETS variable present. Will fallback to external.qt
return None | Return a list of acceptable QT APIs, in decreasing order of preference |
177,655 | import gtk, gobject
def _main_quit(*args, **kwargs):
def create_inputhook_gtk(stdin_file):
def inputhook_gtk():
gobject.io_add_watch(stdin_file, gobject.IO_IN, _main_quit)
gtk.main()
return 0
return inputhook_gtk | null |
177,656 | import os
import signal
import threading
from pydev_ipython.qt_for_kernel import QtCore, QtGui
from pydev_ipython.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
class InteractiveShell:
_instance = None
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def set_hook(self, *args, **kwargs):
# We don't consider the pre_prompt_hook because we don't have
# KeyboardInterrupts to consider since we are running under PyDev
pass
got_kbdint = False
sigint_timer = None
def ignore_CTRL_C():
"""Ignore CTRL+C (not implemented)."""
pass
def allow_CTRL_C():
"""Take CTRL+C into account (not implemented)."""
pass
stdin_ready = inputhook_manager.return_control
The provided code snippet includes necessary dependencies for implementing the `create_inputhook_qt4` function. Write a Python function `def create_inputhook_qt4(mgr, app=None)` to solve the following problem:
Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt4's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt.
Here is the function:
def create_inputhook_qt4(mgr, app=None):
"""Create an input hook for running the Qt4 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt4's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
app = QtGui.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt4'):
return app, ip._inputhook_qt4
# Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
# hooks (they both share the got_kbdint flag)
def inputhook_qt4():
"""PyOS_InputHook python hook for Qt4.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
# Generally a program would run QCoreApplication::exec()
# from main() to enter and process the Qt event loop until
# quit() or exit() is called and the program terminates.
#
# For our input hook integration, we need to repeatedly
# enter and process the Qt event loop for only a short
# amount of time (say 50ms) to ensure that Python stays
# responsive to other user inputs.
#
# A naive approach would be to repeatedly call
# QCoreApplication::exec(), using a timer to quit after a
# short amount of time. Unfortunately, QCoreApplication
# emits an aboutToQuit signal before stopping, which has
# the undesirable effect of closing all modal windows.
#
# To work around this problem, we instead create a
# QEventLoop and call QEventLoop::exec(). Other than
# setting some state variables which do not seem to be
# used anywhere, the only thing QCoreApplication adds is
# the aboutToQuit signal which is precisely what we are
# trying to avoid.
timer = QtCore.QTimer()
event_loop = QtCore.QEventLoop()
timer.timeout.connect(event_loop.quit)
while not stdin_ready():
timer.start(50)
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
global got_kbdint, sigint_timer
ignore_CTRL_C()
got_kbdint = True
mgr.clear_inputhook()
# This generates a second SIGINT so the user doesn't have to
# press CTRL+C twice to get a clean prompt.
#
# Since we can't catch the resulting KeyboardInterrupt here
# (because this is a ctypes callback), we use a timer to
# generate the SIGINT after we leave this callback.
#
# Unfortunately this doesn't work on Windows (SIGINT kills
# Python and CTRL_C_EVENT doesn't work).
if(os.name == 'posix'):
pid = os.getpid()
if(not sigint_timer):
sigint_timer = threading.Timer(.01, os.kill,
args=[pid, signal.SIGINT] )
sigint_timer.start()
else:
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt4, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt4(ishell):
"""'pre_prompt_hook' used to restore the Qt4 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
global got_kbdint, sigint_timer
if(sigint_timer):
sigint_timer.cancel()
sigint_timer = None
if got_kbdint:
mgr.set_inputhook(inputhook_qt4)
got_kbdint = False
ip._inputhook_qt4 = inputhook_qt4
ip.set_hook('pre_prompt_hook', preprompthook_qt4)
return app, inputhook_qt4 | Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt4's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt. |
177,657 | from gi.repository import Gtk, GLib
def _main_quit(*args, **kwargs):
def create_inputhook_gtk3(stdin_file):
def inputhook_gtk3():
GLib.io_add_watch(stdin_file, GLib.IO_IN, _main_quit)
Gtk.main()
return 0
return inputhook_gtk3 | null |
177,658 | import sys
from _pydev_bundle import pydev_log
def versionok_for_gui():
''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration '''
# We require Python 2.6+ ...
if sys.hexversion < 0x02060000:
return False
# Or Python 3.2+
if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000:
return False
# Not supported under Jython nor IronPython
if sys.platform.startswith("java") or sys.platform.startswith('cli'):
return False
return True
def enable_gui(gui=None, app=None):
"""Switch amongst GUI input hooks by name.
This is just a utility wrapper around the methods of the InputHookManager
object.
Parameters
----------
gui : optional, string or None
If None (or 'none'), clears input hook, otherwise it must be one
of the recognized GUI names (see ``GUI_*`` constants in module).
app : optional, existing application object.
For toolkits that have the concept of a global app, you can supply an
existing one. If not given, the toolkit will be probed for one, and if
none is found, a new one will be created. Note that GTK does not have
this concept, and passing an app if ``gui=="GTK"`` will raise an error.
Returns
-------
The output of the underlying gui switch routine, typically the actual
PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
one.
"""
if get_return_control_callback() is None:
raise ValueError("A return_control_callback must be supplied as a reference before a gui can be enabled")
guis = {GUI_NONE: clear_inputhook,
GUI_OSX: enable_mac,
GUI_TK: enable_tk,
GUI_GTK: enable_gtk,
GUI_WX: enable_wx,
GUI_QT: enable_qt,
GUI_QT4: enable_qt4,
GUI_QT5: enable_qt5,
GUI_GLUT: enable_glut,
GUI_PYGLET: enable_pyglet,
GUI_GTK3: enable_gtk3,
}
try:
gui_hook = guis[gui]
except KeyError:
if gui is None or gui == '':
gui_hook = clear_inputhook
else:
e = "Invalid GUI request %r, valid ones are:%s" % (gui, list(guis.keys()))
raise ValueError(e)
return gui_hook(app)
def do_enable_gui(guiname):
from _pydev_bundle.pydev_versioncheck import versionok_for_gui
if versionok_for_gui():
try:
from pydev_ipython.inputhook import enable_gui
enable_gui(guiname)
except:
sys.stderr.write("Failed to enable GUI event loop integration for '%s'\n" % guiname)
pydev_log.exception()
elif guiname not in ['none', '', None]:
# Only print a warning if the guiname was going to do something
sys.stderr.write("Debug console: Python version does not support GUI event loop integration for '%s'\n" % guiname)
# Return value does not matter, so return back what was sent
return guiname | null |
177,659 | import sys
from _pydev_bundle import pydev_log
def find_gui_and_backend():
"""Return the gui and mpl backend."""
matplotlib = sys.modules['matplotlib']
# WARNING: this assumes matplotlib 1.1 or newer!!
backend = matplotlib.rcParams['backend']
# In this case, we need to find what the appropriate gui selection call
# should be for IPython, so we can activate inputhook accordingly
gui = backend2gui.get(backend, None)
return gui, backend
def is_interactive_backend(backend):
""" Check if backend is interactive """
matplotlib = sys.modules['matplotlib']
from matplotlib.rcsetup import interactive_bk, non_interactive_bk # @UnresolvedImport
if backend in interactive_bk:
return True
elif backend in non_interactive_bk:
return False
else:
return matplotlib.is_interactive()
def patch_use(enable_gui_function):
""" Patch matplotlib function 'use' """
matplotlib = sys.modules['matplotlib']
def patched_use(*args, **kwargs):
matplotlib.real_use(*args, **kwargs)
gui, backend = find_gui_and_backend()
enable_gui_function(gui)
matplotlib.real_use = matplotlib.use
matplotlib.use = patched_use
def patch_is_interactive():
""" Patch matplotlib function 'use' """
matplotlib = sys.modules['matplotlib']
def patched_is_interactive():
return matplotlib.rcParams['interactive']
matplotlib.real_is_interactive = matplotlib.is_interactive
matplotlib.is_interactive = patched_is_interactive
The provided code snippet includes necessary dependencies for implementing the `activate_matplotlib` function. Write a Python function `def activate_matplotlib(enable_gui_function)` to solve the following problem:
Set interactive to True for interactive backends. enable_gui_function - Function which enables gui, should be run in the main thread.
Here is the function:
def activate_matplotlib(enable_gui_function):
"""Set interactive to True for interactive backends.
enable_gui_function - Function which enables gui, should be run in the main thread.
"""
matplotlib = sys.modules['matplotlib']
gui, backend = find_gui_and_backend()
is_interactive = is_interactive_backend(backend)
if is_interactive:
enable_gui_function(gui)
if not matplotlib.is_interactive():
sys.stdout.write("Backend %s is interactive backend. Turning interactive mode on.\n" % backend)
matplotlib.interactive(True)
else:
if matplotlib.is_interactive():
sys.stdout.write("Backend %s is non-interactive backend. Turning interactive mode off.\n" % backend)
matplotlib.interactive(False)
patch_use(enable_gui_function)
patch_is_interactive() | Set interactive to True for interactive backends. enable_gui_function - Function which enables gui, should be run in the main thread. |
177,660 | import sys
from _pydev_bundle import pydev_log
def flag_calls(func):
def activate_pylab():
pylab = sys.modules['pylab']
pylab.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) | null |
177,661 | import sys
from _pydev_bundle import pydev_log
def flag_calls(func):
"""Wrap a function to detect and flag when it gets called.
This is a decorator which takes a function and wraps it in a function with
a 'called' attribute. wrapper.called is initialized to False.
The wrapper.called attribute is set to False right before each call to the
wrapped function, so if the call fails it remains False. After the call
completes, wrapper.called is set to True and the output is returned.
Testing for truth in wrapper.called allows you to determine if a call to
func() was attempted and succeeded."""
# don't wrap twice
if hasattr(func, 'called'):
return func
def wrapper(*args, **kw):
wrapper.called = False
out = func(*args, **kw)
wrapper.called = True
return out
wrapper.called = False
wrapper.__doc__ = func.__doc__
return wrapper
def activate_pyplot():
pyplot = sys.modules['matplotlib.pyplot']
pyplot.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pyplot.draw_if_interactive = flag_calls(pyplot.draw_if_interactive) | null |
177,662 |
The provided code snippet includes necessary dependencies for implementing the `overrides` function. Write a Python function `def overrides(method)` to solve the following problem:
Meant to be used as class B: @overrides(A.m1) def m1(self): pass
Here is the function:
def overrides(method):
'''
Meant to be used as
class B:
@overrides(A.m1)
def m1(self):
pass
'''
def wrapper(func):
if func.__name__ != method.__name__:
msg = "Wrong @override: %r expected, but overwriting %r."
msg = msg % (func.__name__, method.__name__)
raise AssertionError(msg)
if func.__doc__ is None:
func.__doc__ = method.__doc__
return func
return wrapper | Meant to be used as class B: @overrides(A.m1) def m1(self): pass |
177,663 |
def implements(method):
def wrapper(func):
if func.__name__ != method.__name__:
msg = "Wrong @implements: %r expected, but implementing %r."
msg = msg % (func.__name__, method.__name__)
raise AssertionError(msg)
if func.__doc__ is None:
func.__doc__ = method.__doc__
return func
return wrapper | null |
177,664 | import types
from _pydevd_bundle.pydevd_constants import IS_JYTHON
try:
import inspect
except:
import traceback;
traceback.print_exc() # Ok, no inspect available (search will not work)
from _pydev_bundle._pydev_imports_tipper import signature_from_docstring
def is_bound_method(obj):
if isinstance(obj, types.MethodType):
return getattr(obj, '__self__', getattr(obj, 'im_self', None)) is not None
else:
return False
def get_class_name(instance):
return getattr(getattr(instance, "__class__", None), "__name__", None)
def get_bound_class_name(obj):
my_self = getattr(obj, '__self__', getattr(obj, 'im_self', None))
if my_self is None:
return None
return get_class_name(my_self)
def create_method_stub(fn_name, fn_class, argspec, doc_string):
if fn_name and argspec:
doc_string = "" if doc_string is None else doc_string
fn_stub = create_function_stub(fn_name, argspec, doc_string, indent=1 if fn_class else 0)
if fn_class:
expr = fn_class if fn_name == '__init__' else fn_class + '().' + fn_name
return create_class_stub(fn_class, fn_stub) + "\n" + expr
else:
expr = fn_name
return fn_stub + "\n" + expr
elif doc_string:
if fn_name:
restored_signature, _ = signature_from_docstring(doc_string, fn_name)
if restored_signature:
return create_method_stub(fn_name, fn_class, restored_signature, doc_string)
return create_function_stub('unknown', '(*args, **kwargs)', doc_string) + '\nunknown'
else:
return ''
def get_docstring(obj):
if obj is not None:
try:
if IS_JYTHON:
# Jython
doc = obj.__doc__
if doc is not None:
return doc
from _pydev_bundle import _pydev_jy_imports_tipper
is_method, infos = _pydev_jy_imports_tipper.ismethod(obj)
ret = ''
if is_method:
for info in infos:
ret += info.get_as_doc()
return ret
else:
doc = inspect.getdoc(obj)
if doc is not None:
return doc
except:
pass
else:
return ''
try:
# if no attempt succeeded, try to return repr()...
return repr(obj)
except:
try:
# otherwise the class
return str(obj.__class__)
except:
# if all fails, go to an empty string
return ''
def get_description(obj):
try:
ob_call = obj.__call__
except:
ob_call = None
if isinstance(obj, type) or type(obj).__name__ == 'classobj':
fob = getattr(obj, '__init__', lambda: None)
if not isinstance(fob, (types.FunctionType, types.MethodType)):
fob = obj
elif is_bound_method(ob_call):
fob = ob_call
else:
fob = obj
argspec = ""
fn_name = None
fn_class = None
if isinstance(fob, (types.FunctionType, types.MethodType)):
spec_info = inspect.getfullargspec(fob)
argspec = inspect.formatargspec(*spec_info)
fn_name = getattr(fob, '__name__', None)
if isinstance(obj, type) or type(obj).__name__ == 'classobj':
fn_name = "__init__"
fn_class = getattr(obj, "__name__", "UnknownClass")
elif is_bound_method(obj) or is_bound_method(ob_call):
fn_class = get_bound_class_name(obj) or "UnknownClass"
else:
fn_name = getattr(fob, '__name__', None)
fn_self = getattr(fob, '__self__', None)
if fn_self is not None and not isinstance(fn_self, types.ModuleType):
fn_class = get_class_name(fn_self)
doc_string = get_docstring(ob_call) if is_bound_method(ob_call) else get_docstring(obj)
return create_method_stub(fn_name, fn_class, argspec, doc_string) | null |
177,665 | from _pydev_bundle._pydev_saved_modules import threading
def is_thread_alive(t):
return not t._is_stopped | null |
177,666 | from _pydev_bundle._pydev_saved_modules import threading
def is_thread_alive(t):
return not t._Thread__stopped | null |
177,667 | from _pydev_bundle._pydev_saved_modules import threading
def is_thread_alive(t):
return t.is_alive() | null |
177,668 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
class _LoggingGlobals(object):
import time
class DebugInfoHolder:
DebugInfoHolder.PYDEVD_DEBUG_FILE = os.getenv('PYDEVD_DEBUG_FILE')
NULL = Null()
def log_to(log_file:str, log_level:int=3) -> None:
with _LoggingGlobals._initialize_lock:
# Can be set directly.
DebugInfoHolder.DEBUG_TRACE_LEVEL = log_level
if DebugInfoHolder.PYDEVD_DEBUG_FILE != log_file:
# Note that we don't need to reset it unless it actually changed
# (would be the case where it's set as an env var in a new process
# and a subprocess initializes logging to the same value).
_LoggingGlobals._debug_stream = NULL
_LoggingGlobals._debug_stream_filename = None
DebugInfoHolder.PYDEVD_DEBUG_FILE = log_file
_LoggingGlobals._debug_stream_initialized = False | null |
177,669 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
import time
def list_log_files(pydevd_debug_file):
log_files = []
dirname = os.path.dirname(pydevd_debug_file)
basename = os.path.basename(pydevd_debug_file)
if os.path.isdir(dirname):
name, ext = os.path.splitext(basename)
for f in os.listdir(dirname):
if f.startswith(name) and f.endswith(ext):
log_files.append(os.path.join(dirname, f))
return log_files | null |
177,670 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
class _LoggingGlobals(object):
_warn_once_map = {}
_debug_stream_filename = None
_debug_stream = NULL
_debug_stream_initialized = False
_initialize_lock = ForkSafeLock()
import time
class DebugInfoHolder:
# we have to put it here because it can be set through the command line (so, the
# already imported references would not have it).
# General information
DEBUG_TRACE_LEVEL = 0 # 0 = critical, 1 = info, 2 = debug, 3 = verbose
PYDEVD_DEBUG_FILE = None
DebugInfoHolder.PYDEVD_DEBUG_FILE = os.getenv('PYDEVD_DEBUG_FILE')
The provided code snippet includes necessary dependencies for implementing the `log_context` function. Write a Python function `def log_context(trace_level, stream)` to solve the following problem:
To be used to temporarily change the logging settings.
Here is the function:
def log_context(trace_level, stream):
'''
To be used to temporarily change the logging settings.
'''
with _LoggingGlobals._initialize_lock:
original_trace_level = DebugInfoHolder.DEBUG_TRACE_LEVEL
original_debug_stream = _LoggingGlobals._debug_stream
original_pydevd_debug_file = DebugInfoHolder.PYDEVD_DEBUG_FILE
original_debug_stream_filename = _LoggingGlobals._debug_stream_filename
original_initialized = _LoggingGlobals._debug_stream_initialized
DebugInfoHolder.DEBUG_TRACE_LEVEL = trace_level
_LoggingGlobals._debug_stream = stream
_LoggingGlobals._debug_stream_initialized = True
try:
yield
finally:
with _LoggingGlobals._initialize_lock:
DebugInfoHolder.DEBUG_TRACE_LEVEL = original_trace_level
_LoggingGlobals._debug_stream = original_debug_stream
DebugInfoHolder.PYDEVD_DEBUG_FILE = original_pydevd_debug_file
_LoggingGlobals._debug_stream_filename = original_debug_stream_filename
_LoggingGlobals._debug_stream_initialized = original_initialized | To be used to temporarily change the logging settings. |
177,671 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
import time
def _pydevd_log(level, msg, *args):
'''
Levels are:
0 most serious warnings/errors (always printed)
1 warnings/significant events
2 informational trace
3 verbose mode
'''
if level <= DebugInfoHolder.DEBUG_TRACE_LEVEL:
# yes, we can have errors printing if the console of the program has been finished (and we're still trying to print something)
try:
try:
if args:
msg = msg % args
except:
msg = '%s - %s' % (msg, args)
if LOG_TIME:
global _last_log_time
new_log_time = time.time()
time_diff = new_log_time - _last_log_time
_last_log_time = new_log_time
msg = '%.2fs - %s\n' % (time_diff, msg,)
else:
msg = '%s\n' % (msg,)
if _LOG_PID:
msg = '<%s> - %s\n' % (os.getpid(), msg,)
try:
try:
initialize_debug_stream() # Do it as late as possible
_LoggingGlobals._debug_stream.write(msg)
except TypeError:
if isinstance(msg, bytes):
# Depending on the StringIO flavor, it may only accept unicode.
msg = msg.decode('utf-8', 'replace')
_LoggingGlobals._debug_stream.write(msg)
except UnicodeEncodeError:
# When writing to the stream it's possible that the string can't be represented
# in the encoding expected (in this case, convert it to the stream encoding
# or ascii if we can't find one suitable using a suitable replace).
encoding = getattr(_LoggingGlobals._debug_stream, 'encoding', 'ascii')
msg = msg.encode(encoding, 'backslashreplace')
msg = msg.decode(encoding)
_LoggingGlobals._debug_stream.write(msg)
_LoggingGlobals._debug_stream.flush()
except:
pass
return True
class DebugInfoHolder:
# we have to put it here because it can be set through the command line (so, the
# already imported references would not have it).
# General information
DEBUG_TRACE_LEVEL = 0 # 0 = critical, 1 = info, 2 = debug, 3 = verbose
PYDEVD_DEBUG_FILE = None
DebugInfoHolder.PYDEVD_DEBUG_FILE = os.getenv('PYDEVD_DEBUG_FILE')
def verbose(msg, *args):
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3:
_pydevd_log(3, msg, *args) | null |
177,672 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
import time
def error_once(msg, *args):
try:
if args:
message = msg % args
else:
message = str(msg)
except:
message = '%s - %s' % (msg, args)
if message not in _LoggingGlobals._warn_once_map:
_LoggingGlobals._warn_once_map[message] = True
critical(message)
class DebugInfoHolder:
# we have to put it here because it can be set through the command line (so, the
# already imported references would not have it).
# General information
DEBUG_TRACE_LEVEL = 0 # 0 = critical, 1 = info, 2 = debug, 3 = verbose
PYDEVD_DEBUG_FILE = None
DebugInfoHolder.PYDEVD_DEBUG_FILE = os.getenv('PYDEVD_DEBUG_FILE')
def debug_once(msg, *args):
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3:
error_once(msg, *args) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.