code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
'''
:param ContinueRequest request:
'''
arguments = request.arguments # : :type arguments: ContinueArguments
thread_id = arguments.threadId
def on_resumed():
body = {'allThreadsContinued': thread_id == '*'}
response = pydevd_base_schema.build_response(request, kwargs={'body': body})
cmd = NetCommand(CMD_RETURN, 0, response, is_json=True)
py_db.writer.add_command(cmd)
# Only send resumed notification when it has actually resumed!
# (otherwise the user could send a continue, receive the notification and then
# request a new pause which would be paused without sending any notification as
# it didn't really run in the first place).
py_db.threads_suspended_single_notification.add_on_resumed_callback(on_resumed)
self.api.request_resume_thread(thread_id) | def on_continue_request(self, py_db, request) | :param ContinueRequest request: | 8.782281 | 8.356419 | 1.050962 |
'''
:param NextRequest request:
'''
arguments = request.arguments # : :type arguments: NextArguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_OVER_MY_CODE
else:
step_cmd_id = CMD_STEP_OVER
self.api.request_step(py_db, thread_id, step_cmd_id)
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_next_request(self, py_db, request) | :param NextRequest request: | 7.453148 | 6.818706 | 1.093044 |
'''
:param StepInRequest request:
'''
arguments = request.arguments # : :type arguments: StepInArguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_INTO_MY_CODE
else:
step_cmd_id = CMD_STEP_INTO
self.api.request_step(py_db, thread_id, step_cmd_id)
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_stepin_request(self, py_db, request) | :param StepInRequest request: | 6.250827 | 5.822225 | 1.073615 |
'''
:param StepOutRequest request:
'''
arguments = request.arguments # : :type arguments: StepOutArguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_RETURN_MY_CODE
else:
step_cmd_id = CMD_STEP_RETURN
self.api.request_step(py_db, thread_id, step_cmd_id)
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_stepout_request(self, py_db, request) | :param StepOutRequest request: | 6.324506 | 5.990938 | 1.055679 |
'''Following hit condition values are supported
* x or == x when breakpoint is hit x times
* >= x when breakpoint is hit more than or equal to x times
* % x when breakpoint is hit multiple of x times
Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits
'''
if not hit_condition:
return None
expr = hit_condition.strip()
try:
int(expr)
return '@HIT@ == {}'.format(expr)
except ValueError:
pass
if expr.startswith('%'):
return '@HIT@ {} == 0'.format(expr)
if expr.startswith('==') or \
expr.startswith('>') or \
expr.startswith('<'):
return '@HIT@ {}'.format(expr)
return hit_condition | def _get_hit_condition_expression(self, hit_condition) | Following hit condition values are supported
* x or == x when breakpoint is hit x times
* >= x when breakpoint is hit more than or equal to x times
* % x when breakpoint is hit multiple of x times
Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits | 5.315064 | 2.095198 | 2.536784 |
'''
:param DisconnectRequest request:
'''
self.api.set_enable_thread_notifications(py_db, False)
self.api.remove_all_breakpoints(py_db, filename='*')
self.api.remove_all_exception_breakpoints(py_db)
self.api.request_resume_thread(thread_id='*')
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_disconnect_request(self, py_db, request) | :param DisconnectRequest request: | 6.954779 | 6.32372 | 1.099792 |
'''
:param SetBreakpointsRequest request:
'''
arguments = request.arguments # : :type arguments: SetBreakpointsArguments
# TODO: Path is optional here it could be source reference.
filename = arguments.source.path
filename = self.api.filename_to_server(filename)
func_name = 'None'
self.api.remove_all_breakpoints(py_db, filename)
# Validate breakpoints and adjust their positions.
try:
lines = sorted(_get_code_lines(filename))
except Exception:
pass
else:
for bp in arguments.breakpoints:
line = bp['line']
if line not in lines:
# Adjust to the first preceding valid line.
idx = bisect.bisect_left(lines, line)
if idx > 0:
bp['line'] = lines[idx - 1]
btype = 'python-line'
suspend_policy = 'ALL'
if not filename.lower().endswith('.py'):
if self._debug_options.get('DJANGO_DEBUG', False):
btype = 'django-line'
elif self._debug_options.get('FLASK_DEBUG', False):
btype = 'jinja2-line'
breakpoints_set = []
for source_breakpoint in arguments.breakpoints:
source_breakpoint = SourceBreakpoint(**source_breakpoint)
line = source_breakpoint.line
condition = source_breakpoint.condition
breakpoint_id = line
hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition)
log_message = source_breakpoint.logMessage
if not log_message:
is_logpoint = None
expression = None
else:
is_logpoint = True
expression = convert_dap_log_message_to_expression(log_message)
self.api.add_breakpoint(
py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint)
# Note that the id is made up (the id for pydevd is unique only within a file, so, the
# line is used for it).
# Also, the id is currently not used afterwards, so, we don't even keep a mapping.
breakpoints_set.append({'id': self._next_breakpoint_id(), 'verified': True, 'line': line})
body = {'breakpoints': breakpoints_set}
set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body': body})
return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True) | def on_setbreakpoints_request(self, py_db, request) | :param SetBreakpointsRequest request: | 4.804055 | 4.738977 | 1.013732 |
'''
:param SetExceptionBreakpointsRequest request:
'''
# : :type arguments: SetExceptionBreakpointsArguments
arguments = request.arguments
filters = arguments.filters
exception_options = arguments.exceptionOptions
self.api.remove_all_exception_breakpoints(py_db)
# Can't set these in the DAP.
condition = None
expression = None
notify_on_first_raise_only = False
ignore_libraries = 1 if py_db.get_use_libraries_filter() else 0
if exception_options:
break_raised = True
break_uncaught = True
for option in exception_options:
option = ExceptionOptions(**option)
if not option.path:
continue
notify_on_handled_exceptions = 1 if option.breakMode == 'always' else 0
notify_on_unhandled_exceptions = 1 if option.breakMode in ('unhandled', 'userUnhandled') else 0
exception_paths = option.path
exception_names = []
if len(exception_paths) == 0:
continue
elif len(exception_paths) == 1:
if 'Python Exceptions' in exception_paths[0]['names']:
exception_names = ['BaseException']
else:
path_iterator = iter(exception_paths)
if 'Python Exceptions' in next(path_iterator)['names']:
for path in path_iterator:
for ex_name in path['names']:
exception_names.append(ex_name)
for exception_name in exception_names:
self.api.add_python_exception_breakpoint(
py_db,
exception_name,
condition,
expression,
notify_on_handled_exceptions,
notify_on_unhandled_exceptions,
notify_on_first_raise_only,
ignore_libraries
)
else:
break_raised = 'raised' in filters
break_uncaught = 'uncaught' in filters
if break_raised or break_uncaught:
notify_on_handled_exceptions = 1 if break_raised else 0
notify_on_unhandled_exceptions = 1 if break_uncaught else 0
exception = 'BaseException'
self.api.add_python_exception_breakpoint(
py_db,
exception,
condition,
expression,
notify_on_handled_exceptions,
notify_on_unhandled_exceptions,
notify_on_first_raise_only,
ignore_libraries
)
if break_raised or break_uncaught:
btype = None
if self._debug_options.get('DJANGO_DEBUG', False):
btype = 'django'
elif self._debug_options.get('FLASK_DEBUG', False):
btype = 'jinja2'
if btype:
self.api.add_plugins_exception_breakpoint(
py_db, btype, 'BaseException') # Note: Exception name could be anything here.
# Note: no body required on success.
set_breakpoints_response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True) | def on_setexceptionbreakpoints_request(self, py_db, request) | :param SetExceptionBreakpointsRequest request: | 3.289071 | 3.26445 | 1.007542 |
'''
:param StackTraceRequest request:
'''
# : :type stack_trace_arguments: StackTraceArguments
stack_trace_arguments = request.arguments
thread_id = stack_trace_arguments.threadId
start_frame = stack_trace_arguments.startFrame
levels = stack_trace_arguments.levels
fmt = stack_trace_arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
self.api.request_stack(py_db, request.seq, thread_id, fmt=fmt, start_frame=start_frame, levels=levels) | def on_stacktrace_request(self, py_db, request) | :param StackTraceRequest request: | 3.398859 | 3.203574 | 1.060959 |
'''
:param ExceptionInfoRequest request:
'''
# : :type exception_into_arguments: ExceptionInfoArguments
exception_into_arguments = request.arguments
thread_id = exception_into_arguments.threadId
max_frames = int(self._debug_options['args'].get('maxExceptionStackFrames', 0))
self.api.request_exception_info_json(py_db, request, thread_id, max_frames) | def on_exceptioninfo_request(self, py_db, request) | :param ExceptionInfoRequest request: | 6.394994 | 6.110456 | 1.046566 |
'''
Scopes are the top-level items which appear for a frame (so, we receive the frame id
and provide the scopes it has).
:param ScopesRequest request:
'''
frame_id = request.arguments.frameId
variables_reference = frame_id
scopes = [Scope('Locals', int(variables_reference), False).to_dict()]
body = ScopesResponseBody(scopes)
scopes_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
return NetCommand(CMD_RETURN, 0, scopes_response, is_json=True) | def on_scopes_request(self, py_db, request) | Scopes are the top-level items which appear for a frame (so, we receive the frame id
and provide the scopes it has).
:param ScopesRequest request: | 11.135204 | 5.898413 | 1.887831 |
'''
:param EvaluateRequest request:
'''
# : :type arguments: EvaluateArguments
arguments = request.arguments
thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference(
arguments.frameId)
self.api.request_exec_or_evaluate_json(
py_db, request, thread_id) | def on_evaluate_request(self, py_db, request) | :param EvaluateRequest request: | 9.05822 | 7.897828 | 1.146926 |
'''
Variables can be asked whenever some place returned a variables reference (so, it
can be a scope gotten from on_scopes_request, the result of some evaluation, etc.).
Note that in the DAP the variables reference requires a unique int... the way this works for
pydevd is that an instance is generated for that specific variable reference and we use its
id(instance) to identify it to make sure all items are unique (and the actual {id->instance}
is added to a dict which is only valid while the thread is suspended and later cleared when
the related thread resumes execution).
see: SuspendedFramesManager
:param VariablesRequest request:
'''
arguments = request.arguments # : :type arguments: VariablesArguments
variables_reference = arguments.variablesReference
thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference(
variables_reference)
if thread_id is not None:
self.api.request_get_variable_json(py_db, request, thread_id)
else:
variables = []
body = VariablesResponseBody(variables)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) | def on_variables_request(self, py_db, request) | Variables can be asked whenever some place returned a variables reference (so, it
can be a scope gotten from on_scopes_request, the result of some evaluation, etc.).
Note that in the DAP the variables reference requires a unique int... the way this works for
pydevd is that an instance is generated for that specific variable reference and we use its
id(instance) to identify it to make sure all items are unique (and the actual {id->instance}
is added to a dict which is only valid while the thread is suspended and later cleared when
the related thread resumes execution).
see: SuspendedFramesManager
:param VariablesRequest request: | 12.06747 | 2.492358 | 4.841789 |
'''
:param SourceRequest request:
'''
source_reference = request.arguments.sourceReference
server_filename = None
content = None
if source_reference != 0:
server_filename = pydevd_file_utils.get_server_filename_from_source_reference(source_reference)
if server_filename:
# Try direct file access first - it's much faster when available.
try:
with open(server_filename, 'r') as stream:
content = stream.read()
except:
pass
if content is None:
# File might not exist at all, or we might not have a permission to read it,
# but it might also be inside a zipfile, or an IPython cell. In this case,
# linecache might still be able to retrieve the source.
lines = (linecache.getline(server_filename, i) for i in itertools.count(1))
lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is ''
# If we didn't get at least one line back, reset it to None so that it's
# reported as error below, and not as an empty file.
content = ''.join(lines) or None
body = SourceResponseBody(content or '')
response_args = {'body': body}
if content is None:
if source_reference == 0:
message = 'Source unavailable'
elif server_filename:
message = 'Unable to retrieve source for %s' % (server_filename,)
else:
message = 'Invalid sourceReference %d' % (source_reference,)
response_args.update({'success': False, 'message': message})
response = pydevd_base_schema.build_response(request, kwargs=response_args)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_source_request(self, py_db, request) | :param SourceRequest request: | 4.488697 | 4.403998 | 1.019232 |
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 | 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. | 6.300139 | 6.481727 | 0.971985 |
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 | 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. | 12.381202 | 9.520974 | 1.300413 |
# 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:
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 | 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. | 5.378597 | 5.260189 | 1.02251 |
base = os.path.basename(path)
filename, ext = os.path.splitext(base)
return filename | def _modname(path) | Return a plausible module name for the path | 2.949223 | 2.949124 | 1.000034 |
'''
It's possible to show paused frames by adding a custom frame through this API (it's
intended to be used for coroutines, but could potentially be used for generators too).
:param frame:
The topmost frame to be shown paused when a thread with thread.ident == thread_id is paused.
:param name:
The name to be shown for the custom thread in the UI.
:param thread_id:
The thread id to which this frame is related (must match thread.ident).
:return: str
Returns the custom thread id which will be used to show the given frame paused.
'''
with CustomFramesContainer.custom_frames_lock:
curr_thread_id = get_current_thread_id(threading.currentThread())
next_id = CustomFramesContainer._next_frame_id = CustomFramesContainer._next_frame_id + 1
# Note: the frame id kept contains an id and thread information on the thread where the frame was added
# so that later on we can check if the frame is from the current thread by doing frame_id.endswith('|'+thread_id).
frame_custom_thread_id = '__frame__:%s|%s' % (next_id, curr_thread_id)
if DEBUG:
sys.stderr.write('add_custom_frame: %s (%s) %s %s\n' % (
frame_custom_thread_id, get_abs_path_real_path_and_base_from_frame(frame)[-1], frame.f_lineno, frame.f_code.co_name))
CustomFramesContainer.custom_frames[frame_custom_thread_id] = CustomFrame(name, frame, thread_id)
CustomFramesContainer._py_db_command_thread_event.set()
return frame_custom_thread_id | def add_custom_frame(frame, name, thread_id) | It's possible to show paused frames by adding a custom frame through this API (it's
intended to be used for coroutines, but could potentially be used for generators too).
:param frame:
The topmost frame to be shown paused when a thread with thread.ident == thread_id is paused.
:param name:
The name to be shown for the custom thread in the UI.
:param thread_id:
The thread id to which this frame is related (must match thread.ident).
:return: str
Returns the custom thread id which will be used to show the given frame paused. | 5.331361 | 2.900304 | 1.838208 |
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, guis.keys())
raise ValueError(e)
return gui_hook(app) | 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. | 3.424129 | 3.056702 | 1.120204 |
if gui is None:
self._apps = {}
elif gui in self._apps:
del self._apps[gui] | def clear_app_refs(self, gui=None) | Clear IPython's internal reference to an application instance.
Whenever we create an app for a user on qt4 or wx, we hold a
reference to the app. This is needed because in some cases bad things
can happen if a user doesn't hold a reference themselves. This
method is provided to clear the references we are holding.
Parameters
----------
gui : None or str
If None, clear all app references. If ('wx', 'qt4') clear
the app for that toolkit. References are not held for gtk or tk
as those toolkits don't have the notion of an app. | 3.330254 | 4.070891 | 0.818065 |
from pydev_ipython.inputhookgtk import create_inputhook_gtk
self.set_inputhook(create_inputhook_gtk(self._stdin_file))
self._current_gui = GUI_GTK | def enable_gtk(self, app=None) | Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython. | 7.759923 | 7.606321 | 1.020194 |
self._current_gui = GUI_TK
if app is None:
try:
import Tkinter as _TK
except:
# Python 3
import tkinter as _TK # @UnresolvedImport
app = _TK.Tk()
app.withdraw()
self._apps[GUI_TK] = app
from pydev_ipython.inputhooktk import create_inputhook_tk
self.set_inputhook(create_inputhook_tk(app))
return app | def enable_tk(self, app=None) | Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``. | 4.063087 | 4.821431 | 0.842714 |
import OpenGL.GLUT as glut # @UnresolvedImport
from pydev_ipython.inputhookglut import glut_display_mode, \
glut_close, glut_display, \
glut_idle, inputhook_glut
if GUI_GLUT not in self._apps:
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut_display_mode)
# This is specific to freeglut
if bool(glut.glutSetOption):
glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
glut.glutCreateWindow(sys.argv[0])
glut.glutReshapeWindow(1, 1)
glut.glutHideWindow()
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
else:
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
self.set_inputhook(inputhook_glut)
self._current_gui = GUI_GLUT
self._apps[GUI_GLUT] = True | def enable_glut(self, app=None) | Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH | 2.769541 | 2.675308 | 1.035224 |
import OpenGL.GLUT as glut # @UnresolvedImport
from glut_support import glutMainLoopEvent # @UnresolvedImport
glut.glutHideWindow() # This is an event to be processed below
glutMainLoopEvent()
self.clear_inputhook() | def disable_glut(self) | Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future. | 6.891568 | 6.608474 | 1.042838 |
from pydev_ipython.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app | def enable_pyglet(self, app=None) | Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython. | 6.42181 | 6.798788 | 0.944552 |
from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3
self.set_inputhook(create_inputhook_gtk3(self._stdin_file))
self._current_gui = GUI_GTK | def enable_gtk3(self, app=None) | Enable event loop integration with Gtk3 (gir bindings).
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for Gtk3, which allows
the Gtk3 to integrate with terminal based applications like
IPython. | 6.861299 | 6.550291 | 1.04748 |
def inputhook_mac(app=None):
if self.pyplot_imported:
pyplot = sys.modules['matplotlib.pyplot']
try:
pyplot.pause(0.01)
except:
pass
else:
if 'matplotlib.pyplot' in sys.modules:
self.pyplot_imported = True
self.set_inputhook(inputhook_mac)
self._current_gui = GUI_OSX | def enable_mac(self, app=None) | Enable event loop integration with MacOSX.
We call function pyplot.pause, which updates and displays active
figure during pause. It's not MacOSX-specific, but it enables to
avoid inputhooks in native MacOSX backend.
Also we shouldn't import pyplot, until user does it. Cause it's
possible to choose backend before importing pyplot for the first
time only. | 4.938467 | 4.004731 | 1.233158 |
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread))
return cmdText | def _thread_to_xml(self, thread) | thread information as XML | 6.456087 | 6.394382 | 1.00965 |
try:
threads = get_non_pydevd_threads()
cmd_text = ["<xml>"]
append = cmd_text.append
for thread in threads:
if is_thread_alive(thread):
append(self._thread_to_xml(thread))
append("</xml>")
return NetCommand(CMD_RETURN, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | def make_list_threads_message(self, py_db, seq) | returns thread listing as XML | 4.528873 | 4.285785 | 1.05672 |
try:
# If frame is None, the return is an empty frame list.
cmd_text = ['<xml><thread id="%s">' % (thread_id,)]
if topmost_frame is not None:
frame_id_to_lineno = {}
try:
# : :type suspended_frames_manager: SuspendedFramesManager
suspended_frames_manager = py_db.suspended_frames_manager
info = suspended_frames_manager.get_topmost_frame_and_frame_id_to_line(thread_id)
if info is None:
# Could not find stack of suspended frame...
if must_be_suspended:
return None
else:
# Note: we have to use the topmost frame where it was suspended (it may
# be different if it was an exception).
topmost_frame, frame_id_to_lineno = info
cmd_text.append(self.make_thread_stack_str(topmost_frame, frame_id_to_lineno))
finally:
topmost_frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_THREAD_STACK, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0) | Returns thread stack as XML.
:param must_be_suspended: If True and the thread is not suspended, returns None. | 3.88948 | 3.787858 | 1.026828 |
'''
:param frame_id_to_lineno:
If available, the line number for the frame will be gotten from this dict,
otherwise frame.f_lineno will be used (needed for unhandled exceptions as
the place where we report may be different from the place where it's raised).
'''
if frame_id_to_lineno is None:
frame_id_to_lineno = {}
make_valid_xml_value = pydevd_xml.make_valid_xml_value
cmd_text_list = []
append = cmd_text_list.append
curr_frame = frame
frame = None # Clear frame reference
try:
py_db = get_global_debugger()
for frame_id, frame, method_name, _original_filename, filename_in_utf8, lineno in self._iter_visible_frames_info(
py_db, curr_frame, frame_id_to_lineno
):
# print("file is ", filename_in_utf8)
# print("line is ", lineno)
# Note: variables are all gotten 'on-demand'.
append('<frame id="%s" name="%s" ' % (frame_id , make_valid_xml_value(method_name)))
append('file="%s" line="%s">' % (quote(make_valid_xml_value(filename_in_utf8), '/>_= \t'), lineno))
append("</frame>")
except:
pydev_log.exception()
curr_frame = None # Clear frame reference
return ''.join(cmd_text_list) | def make_thread_stack_str(self, frame, frame_id_to_lineno=None) | :param frame_id_to_lineno:
If available, the line number for the frame will be gotten from this dict,
otherwise frame.f_lineno will be used (needed for unhandled exceptions as
the place where we report may be different from the place where it's raised). | 4.958248 | 3.479082 | 1.42516 |
make_valid_xml_value = pydevd_xml.make_valid_xml_value
cmd_text_list = []
append = cmd_text_list.append
cmd_text_list.append('<xml>')
if message:
message = make_valid_xml_value(message)
append('<thread id="%s"' % (thread_id,))
if stop_reason is not None:
append(' stop_reason="%s"' % (stop_reason,))
if message is not None:
append(' message="%s"' % (message,))
if suspend_type is not None:
append(' suspend_type="%s"' % (suspend_type,))
append('>')
thread_stack_str = self.make_thread_stack_str(frame, frame_id_to_lineno)
append(thread_stack_str)
append("</thread></xml>")
return ''.join(cmd_text_list), thread_stack_str | def make_thread_suspend_str(
self,
thread_id,
frame,
stop_reason=None,
message=None,
suspend_type="trace",
frame_id_to_lineno=None
) | :return tuple(str,str):
Returns tuple(thread_suspended_str, thread_stack_str).
i.e.:
(
'''
<xml>
<thread id="id" stop_reason="reason">
<frame id="id" name="functionName " file="file" line="line">
</frame>
</thread>
</xml>
'''
,
'''
<frame id="id" name="functionName " file="file" line="line">
</frame>
'''
) | 2.472507 | 2.176734 | 1.135879 |
try:
# If the debugger is not suspended, just return the thread and its id.
cmd_text = ['<xml><thread id="%s" ' % (thread_id,)]
if topmost_frame is not None:
try:
frame = topmost_frame
topmost_frame = None
while frame is not None:
if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'):
arg = frame.f_locals.get('arg', None)
if arg is not None:
exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str(
thread_id, *arg)
cmd_text.append('exc_type="%s" ' % (exc_type,))
cmd_text.append('exc_desc="%s" ' % (exc_desc,))
cmd_text.append('>')
cmd_text.append(thread_stack_str)
break
frame = frame.f_back
else:
cmd_text.append('>')
finally:
frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | def make_get_exception_details_message(self, seq, thread_id, topmost_frame) | Returns exception details as XML | 3.40138 | 3.367005 | 1.010209 |
if process is None:
self.__process = None
else:
global Process # delayed import
if Process is None:
from winappdbg.process import Process
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.__process = process | def set_process(self, process = None) | Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process. | 3.744799 | 3.781302 | 0.990347 |
"Get the size and entry point of the module using the Win32 API."
process = self.get_process()
if process:
try:
handle = process.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
base = self.get_base()
mi = win32.GetModuleInformation(handle, base)
self.SizeOfImage = mi.SizeOfImage
self.EntryPoint = mi.EntryPoint
except WindowsError:
e = sys.exc_info()[1]
warnings.warn(
"Cannot get size and entry point of module %s, reason: %s"\
% (self.get_name(), e.strerror), RuntimeWarning) | def __get_size_and_entry_point(self) | Get the size and entry point of the module using the Win32 API. | 3.648397 | 3.22776 | 1.130319 |
filename = PathOperations.pathname_to_filename(pathname)
if filename:
filename = filename.lower()
filepart, extpart = PathOperations.split_extension(filename)
if filepart and extpart:
modName = filepart
else:
modName = filename
else:
modName = pathname
return modName | def __filename_to_modname(self, pathname) | @type pathname: str
@param pathname: Pathname to a module.
@rtype: str
@return: Module name. | 3.699018 | 4.678958 | 0.790564 |
pathname = self.get_filename()
if pathname:
modName = self.__filename_to_modname(pathname)
if isinstance(modName, compat.unicode):
try:
modName = modName.encode('cp1252')
except UnicodeEncodeError:
e = sys.exc_info()[1]
warnings.warn(str(e))
else:
modName = "0x%x" % self.get_base()
return modName | def get_name(self) | @rtype: str
@return: Module name, as used in labels.
@warning: Names are B{NOT} guaranteed to be unique.
If you need unique identification for a loaded module,
use the base address instead.
@see: L{get_label} | 3.722786 | 3.386311 | 1.099363 |
if not self.get_filename():
msg = "Cannot retrieve filename for module at %s"
msg = msg % HexDump.address( self.get_base() )
raise Exception(msg)
hFile = win32.CreateFile(self.get_filename(),
dwShareMode = win32.FILE_SHARE_READ,
dwCreationDisposition = win32.OPEN_EXISTING)
# In case hFile was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with hFile.
if not hasattr(self.hFile, '__del__'):
self.close_handle()
self.hFile = hFile | def open_handle(self) | Opens a new handle to the module.
The new handle is stored in the L{hFile} property. | 6.081743 | 5.416753 | 1.122766 |
try:
if hasattr(self.hFile, 'close'):
self.hFile.close()
elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hFile)
finally:
self.hFile = None | def close_handle(self) | Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hFile} to C{None} should be enough. | 2.592029 | 2.348277 | 1.103801 |
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_process().get_handle(dwAccess)
hFile = self.hFile
BaseOfDll = self.get_base()
SizeOfDll = self.get_size()
Enumerator = self._SymbolEnumerator()
try:
win32.SymInitialize(hProcess)
SymOptions = win32.SymGetOptions()
SymOptions |= (
win32.SYMOPT_ALLOW_ZERO_ADDRESS |
win32.SYMOPT_CASE_INSENSITIVE |
win32.SYMOPT_FAVOR_COMPRESSED |
win32.SYMOPT_INCLUDE_32BIT_MODULES |
win32.SYMOPT_UNDNAME
)
SymOptions &= ~(
win32.SYMOPT_LOAD_LINES |
win32.SYMOPT_NO_IMAGE_SEARCH |
win32.SYMOPT_NO_CPP |
win32.SYMOPT_IGNORE_NT_SYMPATH
)
win32.SymSetOptions(SymOptions)
try:
win32.SymSetOptions(
SymOptions | win32.SYMOPT_ALLOW_ABSOLUTE_SYMBOLS)
except WindowsError:
pass
try:
try:
success = win32.SymLoadModule64(
hProcess, hFile, None, None, BaseOfDll, SizeOfDll)
except WindowsError:
success = 0
if not success:
ImageName = self.get_filename()
success = win32.SymLoadModule64(
hProcess, None, ImageName, None, BaseOfDll, SizeOfDll)
if success:
try:
win32.SymEnumerateSymbols64(
hProcess, BaseOfDll, Enumerator)
finally:
win32.SymUnloadModule64(hProcess, BaseOfDll)
finally:
win32.SymCleanup(hProcess)
except WindowsError:
e = sys.exc_info()[1]
msg = "Cannot load debug symbols for process ID %d, reason:\n%s"
msg = msg % (self.get_pid(), traceback.format_exc(e))
warnings.warn(msg, DebugSymbolsWarning)
self.__symbols = Enumerator.symbols | def load_symbols(self) | Loads the debugging symbols for a module.
Automatically called by L{get_symbols}. | 3.01022 | 2.957149 | 1.017947 |
if bCaseSensitive:
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName:
return SymbolAddress
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
try:
SymbolName = win32.UnDecorateSymbolName(SymbolName)
except Exception:
continue
if symbol == SymbolName:
return SymbolAddress
else:
symbol = symbol.lower()
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName.lower():
return SymbolAddress
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
try:
SymbolName = win32.UnDecorateSymbolName(SymbolName)
except Exception:
continue
if symbol == SymbolName.lower():
return SymbolAddress | def resolve_symbol(self, symbol, bCaseSensitive = False) | Resolves a debugging symbol's address.
@type symbol: str
@param symbol: Name of the symbol to resolve.
@type bCaseSensitive: bool
@param bCaseSensitive: C{True} for case sensitive matches,
C{False} for case insensitive.
@rtype: int or None
@return: Memory address of symbol. C{None} if not found. | 1.776796 | 1.873079 | 0.948596 |
return _ModuleContainer.parse_label(self.get_name(), function, offset) | def get_label(self, function = None, offset = None) | Retrieves the label for the given function of this module or the module
base address if no function name is given.
@type function: str
@param function: (Optional) Exported function name.
@type offset: int
@param offset: (Optional) Offset from the module base address.
@rtype: str
@return: Label for the module base address, plus the offset if given. | 20.801996 | 29.324886 | 0.709363 |
# Add the offset to the address.
if offset:
address = address + offset
# Make the label relative to the base address if no match is found.
module = self.get_name()
function = None
offset = address - self.get_base()
# Make the label relative to the entrypoint if no other match is found.
# Skip if the entry point is unknown.
start = self.get_entry_point()
if start and start <= address:
function = "start"
offset = address - start
# Enumerate exported functions and debug symbols,
# then find the closest match, if possible.
try:
symbol = self.get_symbol_at_address(address)
if symbol:
(SymbolName, SymbolAddress, SymbolSize) = symbol
new_offset = address - SymbolAddress
if new_offset <= offset:
function = SymbolName
offset = new_offset
except WindowsError:
pass
# Parse the label and return it.
return _ModuleContainer.parse_label(module, function, offset) | def get_label_at_address(self, address, offset = None) | Creates a label from the given memory address.
If the address belongs to the module, the label is made relative to
it's base address.
@type address: int
@param address: Memory address.
@type offset: None or int
@param offset: (Optional) Offset value.
@rtype: str
@return: Label pointing to the given address. | 4.767276 | 4.701653 | 1.013957 |
base = self.get_base()
size = self.get_size()
if base and size:
return base <= address < (base + size)
return None | def is_address_here(self, address) | Tries to determine if the given address belongs to this module.
@type address: int
@param address: Memory address.
@rtype: bool or None
@return: C{True} if the address belongs to the module,
C{False} if it doesn't,
and C{None} if it can't be determined. | 4.224517 | 4.538985 | 0.930718 |
# Unknown DLL filename, there's nothing we can do.
filename = self.get_filename()
if not filename:
return None
# If the DLL is already mapped locally, resolve the function.
try:
hlib = win32.GetModuleHandle(filename)
address = win32.GetProcAddress(hlib, function)
except WindowsError:
# Load the DLL locally, resolve the function and unload it.
try:
hlib = win32.LoadLibraryEx(filename,
win32.DONT_RESOLVE_DLL_REFERENCES)
try:
address = win32.GetProcAddress(hlib, function)
finally:
win32.FreeLibrary(hlib)
except WindowsError:
return None
# A NULL pointer means the function was not found.
if address in (None, 0):
return None
# Compensate for DLL base relocations locally and remotely.
return address - hlib + self.lpBaseOfDll | def resolve(self, function) | Resolves a function exported by this module.
@type function: str or int
@param function:
str: Name of the function.
int: Ordinal of the function.
@rtype: int
@return: Memory address of the exported function in the process.
Returns None on error. | 4.178204 | 4.146778 | 1.007578 |
# Split the label into it's components.
# Use the fuzzy mode whenever possible.
aProcess = self.get_process()
if aProcess is not None:
(module, procedure, offset) = aProcess.split_label(label)
else:
(module, procedure, offset) = _ModuleContainer.split_label(label)
# If a module name is given that doesn't match ours,
# raise an exception.
if module and not self.match_name(module):
raise RuntimeError("Label does not belong to this module")
# Resolve the procedure if given.
if procedure:
address = self.resolve(procedure)
if address is None:
# If it's a debug symbol, use the symbol.
address = self.resolve_symbol(procedure)
# If it's the keyword "start" use the entry point.
if address is None and procedure == "start":
address = self.get_entry_point()
# The procedure was not found.
if address is None:
if not module:
module = self.get_name()
msg = "Can't find procedure %s in module %s"
raise RuntimeError(msg % (procedure, module))
# If no procedure is given use the base address of the module.
else:
address = self.get_base()
# Add the offset if given and return the resolved address.
if offset:
address = address + offset
return address | def resolve_label(self, label) | Resolves a label for this module only. If the label refers to another
module, an exception is raised.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function. | 3.800634 | 3.542584 | 1.072843 |
self.__initialize_snapshot()
if lpBaseOfDll not in self.__moduleDict:
msg = "Unknown DLL base address %s"
msg = msg % HexDump.address(lpBaseOfDll)
raise KeyError(msg)
return self.__moduleDict[lpBaseOfDll] | def get_module(self, lpBaseOfDll) | @type lpBaseOfDll: int
@param lpBaseOfDll: Base address of the DLL to look for.
@rtype: L{Module}
@return: Module object with the given base address. | 4.907117 | 4.958404 | 0.989657 |
# Convert modName to lowercase.
# This helps make case insensitive string comparisons.
modName = modName.lower()
# modName is an absolute pathname.
if PathOperations.path_is_absolute(modName):
for lib in self.iter_modules():
if modName == lib.get_filename().lower():
return lib
return None # Stop trying to match the name.
# Get all the module names.
# This prevents having to iterate through the module list
# more than once.
modDict = [ ( lib.get_name(), lib ) for lib in self.iter_modules() ]
modDict = dict(modDict)
# modName is a base filename.
if modName in modDict:
return modDict[modName]
# modName is a base filename without extension.
filepart, extpart = PathOperations.split_extension(modName)
if filepart and extpart:
if filepart in modDict:
return modDict[filepart]
# modName is a base address.
try:
baseAddress = HexInput.integer(modName)
except ValueError:
return None
if self.has_module(baseAddress):
return self.get_module(baseAddress)
# Module not found.
return None | def get_module_by_name(self, modName) | @type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
You can also pass a full pathname to the DLL file.
This works correctly even if two modules with the same name
are loaded from different paths.
@rtype: L{Module}
@return: C{Module} object that best matches the given name.
Returns C{None} if no C{Module} can be found. | 3.838359 | 3.691705 | 1.039725 |
bases = self.get_module_bases()
bases.sort()
bases.append(long(0x10000000000000000)) # max. 64 bit address + 1
if address >= bases[0]:
i = 0
max_i = len(bases) - 1
while i < max_i:
begin, end = bases[i:i+2]
if begin <= address < end:
module = self.get_module(begin)
here = module.is_address_here(address)
if here is False:
break
else: # True or None
return module
i = i + 1
return None | def get_module_at_address(self, address) | @type address: int
@param address: Memory address to query.
@rtype: L{Module}
@return: C{Module} object that best matches the given address.
Returns C{None} if no C{Module} can be found. | 3.424057 | 3.445581 | 0.993753 |
# The module filenames may be spoofed by malware,
# since this information resides in usermode space.
# See: http://www.ragestorm.net/blogs/?p=163
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
# It would seem easier to clear the snapshot first.
# But then all open handles would be closed.
found_bases = set()
with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPMODULE,
dwProcessId) as hSnapshot:
me = win32.Module32First(hSnapshot)
while me is not None:
lpBaseAddress = me.modBaseAddr
fileName = me.szExePath # full pathname
if not fileName:
fileName = me.szModule # filename only
if not fileName:
fileName = None
else:
fileName = PathOperations.native_to_win32_pathname(fileName)
found_bases.add(lpBaseAddress)
## if not self.has_module(lpBaseAddress): # XXX triggers a scan
if lpBaseAddress not in self.__moduleDict:
aModule = Module(lpBaseAddress, fileName = fileName,
SizeOfImage = me.modBaseSize,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseAddress)
if not aModule.fileName:
aModule.fileName = fileName
if not aModule.SizeOfImage:
aModule.SizeOfImage = me.modBaseSize
if not aModule.process:
aModule.process = self
me = win32.Module32Next(hSnapshot)
## for base in self.get_module_bases(): # XXX triggers a scan
for base in compat.keys(self.__moduleDict):
if base not in found_bases:
self._del_module(base) | def scan_modules(self) | Populates the snapshot with loaded modules. | 6.032227 | 5.828754 | 1.034908 |
for aModule in compat.itervalues(self.__moduleDict):
aModule.clear()
self.__moduleDict = dict() | def clear_modules(self) | Clears the modules snapshot. | 6.927731 | 6.630855 | 1.044772 |
# TODO
# Invalid characters should be escaped or filtered.
# Convert ordinals to strings.
try:
function = "#0x%x" % function
except TypeError:
pass
# Validate the parameters.
if module is not None and ('!' in module or '+' in module):
raise ValueError("Invalid module name: %s" % module)
if function is not None and ('!' in function or '+' in function):
raise ValueError("Invalid function name: %s" % function)
# Parse the label.
if module:
if function:
if offset:
label = "%s!%s+0x%x" % (module, function, offset)
else:
label = "%s!%s" % (module, function)
else:
if offset:
## label = "%s+0x%x!" % (module, offset)
label = "%s!0x%x" % (module, offset)
else:
label = "%s!" % module
else:
if function:
if offset:
label = "!%s+0x%x" % (function, offset)
else:
label = "!%s" % function
else:
if offset:
label = "0x%x" % offset
else:
label = "0x0"
return label | def parse_label(module = None, function = None, offset = None) | Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: str
@return:
Label representing the given function in the given module.
@raise ValueError:
The module or function name contain invalid characters. | 2.154289 | 2.070495 | 1.040471 |
module = function = None
offset = 0
# Special case: None
if not label:
label = "0x0"
else:
# Remove all blanks.
label = label.replace(' ', '')
label = label.replace('\t', '')
label = label.replace('\r', '')
label = label.replace('\n', '')
# Special case: empty label.
if not label:
label = "0x0"
# * ! *
if '!' in label:
try:
module, function = label.split('!')
except ValueError:
raise ValueError("Malformed label: %s" % label)
# module ! function
if function:
if '+' in module:
raise ValueError("Malformed label: %s" % label)
# module ! function + offset
if '+' in function:
try:
function, offset = function.split('+')
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
else:
# module ! offset
try:
offset = HexInput.integer(function)
function = None
except ValueError:
pass
else:
# module + offset !
if '+' in module:
try:
module, offset = module.split('+')
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
else:
# module !
try:
offset = HexInput.integer(module)
module = None
# offset !
except ValueError:
pass
if not module:
module = None
if not function:
function = None
# *
else:
# offset
try:
offset = HexInput.integer(label)
# # ordinal
except ValueError:
if label.startswith('#'):
function = label
try:
HexInput.integer(function[1:])
# module?
# function?
except ValueError:
raise ValueError("Ambiguous label: %s" % label)
# module?
# function?
else:
raise ValueError("Ambiguous label: %s" % label)
# Convert function ordinal strings into integers.
if function and function.startswith('#'):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset) | def split_label_strict(label) | Splits a label created with L{parse_label}.
To parse labels with a less strict syntax, use the L{split_label_fuzzy}
method instead.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed. | 2.519669 | 2.393732 | 1.052611 |
module = function = None
offset = 0
# Special case: None
if not label:
label = compat.b("0x0")
else:
# Remove all blanks.
label = label.replace(compat.b(' '), compat.b(''))
label = label.replace(compat.b('\t'), compat.b(''))
label = label.replace(compat.b('\r'), compat.b(''))
label = label.replace(compat.b('\n'), compat.b(''))
# Special case: empty label.
if not label:
label = compat.b("0x0")
# If an exclamation sign is present, we know we can parse it strictly.
if compat.b('!') in label:
return self.split_label_strict(label)
## # Try to parse it strictly, on error do it the fuzzy way.
## try:
## return self.split_label(label)
## except ValueError:
## pass
# * + offset
if compat.b('+') in label:
try:
prefix, offset = label.split(compat.b('+'))
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
label = prefix
# This parses both filenames and base addresses.
modobj = self.get_module_by_name(label)
if modobj:
# module
# module + offset
module = modobj.get_name()
else:
# TODO
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, it'd be good to add A+B and try to
# use the nearest loaded module.
# offset
# base address + offset (when no module has that base address)
try:
address = HexInput.integer(label)
if offset:
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, we get here, meaning no module was found
# at A. Then add up A+B and work with that as a hardcoded
# address.
offset = address + offset
else:
# If the label is a hardcoded address, we get here.
offset = address
# If only a hardcoded address is given,
# rebuild the label using get_label_at_address.
# Then parse it again, but this time strictly,
# both because there is no need for fuzzy syntax and
# to prevent an infinite recursion if there's a bug here.
try:
new_label = self.get_label_at_address(offset)
module, function, offset = \
self.split_label_strict(new_label)
except ValueError:
pass
# function
# function + offset
except ValueError:
function = label
# Convert function ordinal strings into integers.
if function and function.startswith(compat.b('#')):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset) | def split_label_fuzzy(self, label) | Splits a label entered as user input.
It's more flexible in it's syntax parsing than the L{split_label_strict}
method, as it allows the exclamation mark (B{C{!}}) to be omitted. The
ambiguity is resolved by searching the modules in the snapshot to guess
if a label refers to a module or a function. It also tries to rebuild
labels when they contain hardcoded addresses.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed. | 4.514344 | 4.238079 | 1.065186 |
(module, function, offset) = self.split_label_fuzzy(label)
label = self.parse_label(module, function, offset)
return label | def sanitize_label(self, label) | Converts a label taken from user input into a well-formed label.
@type label: str
@param label: Label taken from user input.
@rtype: str
@return: Sanitized label. | 8.677685 | 10.810368 | 0.802719 |
# Split the label into module, function and offset components.
module, function, offset = self.split_label_fuzzy(label)
# Resolve the components into a memory address.
address = self.resolve_label_components(module, function, offset)
# Return the memory address.
return address | def resolve_label(self, label) | Resolve the memory address of the given label.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function. | 4.861441 | 4.471062 | 1.087312 |
# Default address if no module or function are given.
# An offset may be added later.
address = 0
# Resolve the module.
# If the module is not found, check for the special symbol "main".
if module:
modobj = self.get_module_by_name(module)
if not modobj:
if module == "main":
modobj = self.get_main_module()
else:
raise RuntimeError("Module %r not found" % module)
# Resolve the exported function or debugging symbol.
# If all else fails, check for the special symbol "start".
if function:
address = modobj.resolve(function)
if address is None:
address = modobj.resolve_symbol(function)
if address is None:
if function == "start":
address = modobj.get_entry_point()
if address is None:
msg = "Symbol %r not found in module %s"
raise RuntimeError(msg % (function, module))
# No function, use the base address.
else:
address = modobj.get_base()
# Resolve the function in any module.
# If all else fails, check for the special symbols "main" and "start".
elif function:
for modobj in self.iter_modules():
address = modobj.resolve(function)
if address is not None:
break
if address is None:
if function == "start":
modobj = self.get_main_module()
address = modobj.get_entry_point()
elif function == "main":
modobj = self.get_main_module()
address = modobj.get_base()
else:
msg = "Function %r not found in any module" % function
raise RuntimeError(msg)
# Return the address plus the offset.
if offset:
address = address + offset
return address | def resolve_label_components(self, module = None,
function = None,
offset = None) | Resolve the memory address of the given module, function and/or offset.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function. | 2.4558 | 2.457693 | 0.99923 |
if offset:
address = address + offset
modobj = self.get_module_at_address(address)
if modobj:
label = modobj.get_label_at_address(address)
else:
label = self.parse_label(None, None, address)
return label | def get_label_at_address(self, address, offset = None) | Creates a label from the given memory address.
@warning: This method uses the name of the nearest currently loaded
module. If that module is unloaded later, the label becomes
impossible to resolve.
@type address: int
@param address: Memory address.
@type offset: None or int
@param offset: (Optional) Offset value.
@rtype: str
@return: Label pointing to the given address. | 2.814213 | 3.434668 | 0.819355 |
if address:
module = self.get_module_at_address(address)
if module:
return module.match_name("ntdll") or \
module.match_name("kernel32")
return False | def is_system_defined_breakpoint(self, address) | @type address: int
@param address: Memory address.
@rtype: bool
@return: C{True} if the given address points to a system defined
breakpoint. System defined breakpoints are hardcoded into
system libraries. | 5.062669 | 5.733245 | 0.883037 |
symbols = list()
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
symbols.append(symbol)
return symbols | def get_symbols(self) | Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes | 4.359579 | 4.313178 | 1.010758 |
if bCaseSensitive:
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName:
return SymbolAddress
else:
symbol = symbol.lower()
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName.lower():
return SymbolAddress | def resolve_symbol(self, symbol, bCaseSensitive = False) | Resolves a debugging symbol's address.
@type symbol: str
@param symbol: Name of the symbol to resolve.
@type bCaseSensitive: bool
@param bCaseSensitive: C{True} for case sensitive matches,
C{False} for case insensitive.
@rtype: int or None
@return: Memory address of symbol. C{None} if not found. | 2.184067 | 2.47875 | 0.881116 |
# Any module may have symbols pointing anywhere in memory, so there's
# no easy way to optimize this. I guess we're stuck with brute force.
found = None
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if SymbolAddress > address:
continue
if SymbolAddress == address:
found = (SymbolName, SymbolAddress, SymbolSize)
break
if SymbolAddress < address:
if found and (address - found[1]) < (address - SymbolAddress):
continue
else:
found = (SymbolName, SymbolAddress, SymbolSize)
return found | def get_symbol_at_address(self, address) | Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched. | 4.402951 | 4.30148 | 1.02359 |
## if not isinstance(aModule, Module):
## if hasattr(aModule, '__class__'):
## typename = aModule.__class__.__name__
## else:
## typename = str(type(aModule))
## msg = "Expected Module, got %s instead" % typename
## raise TypeError(msg)
lpBaseOfDll = aModule.get_base()
## if lpBaseOfDll in self.__moduleDict:
## msg = "Module already exists: %d" % lpBaseOfDll
## raise KeyError(msg)
aModule.set_process(self)
self.__moduleDict[lpBaseOfDll] = aModule | def _add_module(self, aModule) | Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object. | 2.840707 | 2.888948 | 0.983301 |
try:
aModule = self.__moduleDict[lpBaseOfDll]
del self.__moduleDict[lpBaseOfDll]
except KeyError:
aModule = None
msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll)
warnings.warn(msg, RuntimeWarning)
if aModule:
aModule.clear() | def _del_module(self, lpBaseOfDll) | Private method to remove a module object from the snapshot.
@type lpBaseOfDll: int
@param lpBaseOfDll: Module base address. | 3.724572 | 3.989701 | 0.933547 |
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll not in self.__moduleDict:
fileName = event.get_filename()
if not fileName:
fileName = None
if hasattr(event, 'get_start_address'):
EntryPoint = event.get_start_address()
else:
EntryPoint = None
aModule = Module(lpBaseOfDll, hFile, fileName = fileName,
EntryPoint = EntryPoint,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseOfDll)
if not aModule.hFile and hFile not in (None, 0,
win32.INVALID_HANDLE_VALUE):
aModule.hFile = hFile
if not aModule.process:
aModule.process = self
if aModule.EntryPoint is None and \
hasattr(event, 'get_start_address'):
aModule.EntryPoint = event.get_start_address()
if not aModule.fileName:
fileName = event.get_filename()
if fileName:
aModule.fileName = fileName | def __add_loaded_module(self, event) | Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object. | 3.17276 | 3.198493 | 0.991955 |
lpBaseOfDll = event.get_module_base()
## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll in self.__moduleDict:
self._del_module(lpBaseOfDll)
return True | def _notify_unload_dll(self, event) | Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise. | 8.041558 | 9.054236 | 0.888154 |
frame_variables = self.get_namespace()
var_objects = []
vars = scope_attrs.split(NEXT_VALUE_SEPARATOR)
for var_attrs in vars:
if '\t' in var_attrs:
name, attrs = var_attrs.split('\t', 1)
else:
name = var_attrs
attrs = None
if name in frame_variables:
var_object = pydevd_vars.resolve_var_object(frame_variables[name], attrs)
var_objects.append((var_object, name))
else:
var_object = pydevd_vars.eval_in_context(name, frame_variables, frame_variables)
var_objects.append((var_object, name))
from _pydevd_bundle.pydevd_comm import GetValueAsyncThreadConsole
t = GetValueAsyncThreadConsole(self.get_server(), seq, var_objects)
t.start() | def loadFullValue(self, seq, scope_attrs) | Evaluate full value for async Console variables in a separate thread and send results to IDE side
:param seq: id of command
:param scope_attrs: a sequence of variables with their attributes separated by NEXT_VALUE_SEPARATOR
(i.e.: obj\tattr1\tattr2NEXT_VALUE_SEPARATORobj2\attr1\tattr2)
:return: | 3.546156 | 2.893473 | 1.225571 |
'''
Used to show console with variables connection.
Mainly, monkey-patches things in the debugger structure so that the debugger protocol works.
'''
if debugger_options is None:
debugger_options = {}
env_key = "PYDEVD_EXTRA_ENVS"
if env_key in debugger_options:
for (env_name, value) in dict_iter_items(debugger_options[env_key]):
existing_value = os.environ.get(env_name, None)
if existing_value:
os.environ[env_name] = "%s%c%s" % (existing_value, os.path.pathsep, value)
else:
os.environ[env_name] = value
if env_name == "PYTHONPATH":
sys.path.append(value)
del debugger_options[env_key]
def do_connect_to_debugger():
try:
# Try to import the packages needed to attach the debugger
import pydevd
from _pydev_imps._pydev_saved_modules import threading
except:
# This happens on Jython embedded in host eclipse
traceback.print_exc()
sys.stderr.write('pydevd is not available, cannot connect\n', )
from _pydevd_bundle.pydevd_constants import set_thread_id
from _pydev_bundle import pydev_localhost
set_thread_id(threading.currentThread(), "console_main")
VIRTUAL_FRAME_ID = "1" # matches PyStackFrameConsole.java
VIRTUAL_CONSOLE_ID = "console_main" # matches PyThreadConsole.java
f = FakeFrame()
f.f_back = None
f.f_globals = {} # As globals=locals here, let's simply let it empty (and save a bit of network traffic).
f.f_locals = self.get_namespace()
self.debugger = pydevd.PyDB()
self.debugger.add_fake_frame(thread_id=VIRTUAL_CONSOLE_ID, frame_id=VIRTUAL_FRAME_ID, frame=f)
try:
pydevd.apply_debugger_options(debugger_options)
self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
self.debugger.prepare_to_run()
self.debugger.disable_tracing()
except:
traceback.print_exc()
sys.stderr.write('Failed to connect to target debugger.\n')
# Register to process commands when idle
self.debugrunning = False
try:
import pydevconsole
pydevconsole.set_debug_hook(self.debugger.process_internal_commands)
except:
traceback.print_exc()
sys.stderr.write('Version of Python does not support debuggable Interactive Console.\n')
# Important: it has to be really enabled in the main thread, so, schedule
# it to run in the main thread.
self.exec_queue.put(do_connect_to_debugger)
return ('connect complete',) | def connectToDebugger(self, debuggerPort, debugger_options=None) | Used to show console with variables connection.
Mainly, monkey-patches things in the debugger structure so that the debugger protocol works. | 5.012624 | 4.260941 | 1.176413 |
''' Enable the GUI specified in guiname (see inputhook for list).
As with IPython, enabling multiple GUIs isn't an error, but
only the last one's main loop runs and it may not work
'''
def do_enable_gui():
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)
traceback.print_exc()
elif guiname not in ['none', '', None]:
# Only print a warning if the guiname was going to do something
sys.stderr.write("PyDev 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
# Important: it has to be really enabled in the main thread, so, schedule
# it to run in the main thread.
self.exec_queue.put(do_enable_gui) | def enableGui(self, guiname) | Enable the GUI specified in guiname (see inputhook for list).
As with IPython, enabling multiple GUIs isn't an error, but
only the last one's main loop runs and it may not work | 7.480061 | 4.501687 | 1.661613 |
'''
Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem.
'''
# TODO: Needs better investigation!
global _cache
if _cache is None:
try:
for addr_info in socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP):
config = addr_info[4]
if config[0] == '127.0.0.1':
_cache = '127.0.0.1'
return _cache
except:
# Ok, some versions of Python don't have getaddrinfo or SOL_TCP... Just consider it 127.0.0.1 in this case.
_cache = '127.0.0.1'
else:
_cache = 'localhost'
return _cache | def get_localhost() | Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem. | 5.391475 | 2.517644 | 2.141476 |
# Use the default architecture if none specified.
if not arch:
arch = win32.arch
# Validate the architecture.
if arch not in self.supported:
msg = "The %s engine cannot decode %s code."
msg = msg % (self.name, arch)
raise NotImplementedError(msg)
# Return the architecture.
return arch | def _validate_arch(self, arch = None) | @type arch: str
@param arch: Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@rtype: str
@return: Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@raise NotImplementedError: This disassembler doesn't support the
requested processor architecture. | 4.948049 | 4.468352 | 1.107354 |
if api == QT_API_PYSIDE:
ID.forbid('PyQt4')
ID.forbid('PyQt5')
else:
ID.forbid('PySide') | def commit_api(api) | Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports | 8.175853 | 7.58045 | 1.078545 |
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 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None | 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', 'pyqt', or 'pyqtv1' | 3.085039 | 2.756208 | 1.119306 |
# 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_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 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 | 4.307054 | 4.072058 | 1.057709 |
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 can_import(api) | Safely query whether an API is importable, without importing it | 5.609641 | 5.750294 | 0.97554 |
# 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_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 | 4.586782 | 4.720096 | 0.971756 |
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_pyqt5() | Import PyQt5
ImportErrors raised within this function are non-recoverable | 4.342284 | 5.328689 | 0.814888 |
loaders = {QT_API_PYSIDE: import_pyside,
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" %
(api, 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( % (loaded_api(),
has_binding(QT_API_PYQT),
has_binding(QT_API_PYQT5),
has_binding(QT_API_PYSIDE),
api_options)) | 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) | 3.551085 | 3.497682 | 1.015268 |
try:
ind_c = args.index('-c')
except ValueError:
return -1
else:
for i in range(1, ind_c):
if not args[i].startswith('-'):
# there is an arg without "-" before "-c", so it's not an interpreter's option
return -1
return ind_c | def get_c_option_index(args) | Get index of "-c" argument and check if it's interpreter's option
:param args: list of arguments
:return: index of "-c" if it's an interpreter's option and -1 if it doesn't exist or program's option | 4.75304 | 3.332122 | 1.42643 |
def new_execve(path, args, env):
import os
send_process_created_message()
return getattr(os, original_name)(path, patch_args(args), env)
return new_execve | def create_execve(original_name) | os.execve(path, args, env)
os.execvpe(file, args, env) | 6.451482 | 5.819801 | 1.10854 |
def new_spawnve(mode, path, args, env):
import os
send_process_created_message()
return getattr(os, original_name)(mode, path, patch_args(args), env)
return new_spawnve | def create_spawnve(original_name) | os.spawnve(mode, path, args, env)
os.spawnvpe(mode, file, args, env) | 9.170001 | 5.512483 | 1.663497 |
def new_fork_exec(args, *other_args):
import _posixsubprocess # @UnresolvedImport
args = patch_args(args)
send_process_created_message()
return getattr(_posixsubprocess, original_name)(args, *other_args)
return new_fork_exec | def create_fork_exec(original_name) | _posixsubprocess.fork_exec(args, executable_list, close_fds, ... (13 more)) | 5.549675 | 5.73215 | 0.968166 |
def new_warn_fork_exec(*args):
try:
import _posixsubprocess
warn_multiproc()
return getattr(_posixsubprocess, original_name)(*args)
except:
pass
return new_warn_fork_exec | def create_warn_fork_exec(original_name) | _posixsubprocess.fork_exec(args, executable_list, close_fds, ... (13 more)) | 4.762101 | 5.313024 | 0.896307 |
def new_CreateProcess(app_name, cmd_line, *args):
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
send_process_created_message()
return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
return new_CreateProcess | def create_CreateProcess(original_name) | CreateProcess(*args, **kwargs) | 5.538252 | 5.572635 | 0.99383 |
def new_CreateProcess(*args):
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
warn_multiproc()
return getattr(_subprocess, original_name)(*args)
return new_CreateProcess | def create_CreateProcessWarnMultiproc(original_name) | CreateProcess(*args, **kwargs) | 3.853417 | 3.884682 | 0.991952 |
if not encoding:
encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)
return io.open(filename, mode=mode, encoding=encoding,
newline='') | def open_with_encoding(filename,
encoding=None, mode='r', limit_byte_check=-1) | Return opened file with a specific encoding. | 2.609276 | 2.546822 | 1.024522 |
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0') | def extended_blank_lines(logical_line,
blank_lines,
blank_before,
indent_level,
previous_logical) | Check for missing blank lines after class declaration. | 4.202774 | 3.97787 | 1.056539 |
# Optimization.
return source
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))
fixed_lines = []
sio = io.StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
if (
line.lstrip().startswith('#') and
line_number not in ignored_line_numbers and
not pycodestyle.noqa(line)
):
indentation = _get_indentation(line)
line = line.lstrip()
# Normalize beginning if not a shebang.
if len(line) > 1:
pos = next((index for index, c in enumerate(line)
if c != '#'))
if (
# Leave multiple spaces like '# ' alone.
(line[:pos].count('#') > 1 or line[1].isalnum()) and
# Leave stylistic outlined blocks alone.
not line.rstrip().endswith('#')
):
line = '# ' + line.lstrip('# \t')
fixed_lines.append(indentation + line)
else:
fixed_lines.append(line)
return ''.join(fixed_lines) | def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
if '#' not in source | Format block comments. | 4.524383 | 4.488151 | 1.008073 |
check_lib2to3()
from lib2to3 import pgen2
try:
new_text = refactor_with_2to3(source,
fixer_names=fixer_names,
filename=filename)
except (pgen2.parse.ParseError,
SyntaxError,
UnicodeDecodeError,
UnicodeEncodeError):
return source
if ignore:
if ignore in new_text and ignore not in source:
return source
return new_text | def refactor(source, fixer_names, ignore=None, filename='') | Return refactored code using lib2to3.
Skip if ignore string is produced in the refactored code. | 4.129858 | 3.732856 | 1.106353 |
if not aggressive:
return source
select = select or []
ignore = ignore or []
return refactor(source,
code_to_2to3(select=select,
ignore=ignore),
filename=filename) | def fix_2to3(source,
aggressive=True, select=None, ignore=None, filename='') | Fix various deprecated code (via lib2to3). | 4.999713 | 4.924192 | 1.015337 |
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' | def _get_indentation(line) | Return leading whitespace. | 3.039258 | 2.461735 | 1.2346 |
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702',
# Things that make lines longer.
'e225', 'e231',
# Remove extraneous whitespace before breaking lines.
'e201',
# Shorten whitespace in comment before resorting to wrapping.
'e262'
]
middle_index = 10000
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501'
]
key = pep8_result['id'].lower()
try:
return priority.index(key)
except ValueError:
try:
return middle_index + lowest_priority.index(key) + 1
except ValueError:
return middle_index | def _priority_key(pep8_result) | Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation. | 7.663774 | 7.517441 | 1.019466 |
if line.startswith('def ') and line.rstrip().endswith(':'):
return line + ' pass'
elif line.startswith('return '):
return 'def _(): ' + line
elif line.startswith('@'):
return line + 'def _(): pass'
elif line.startswith('class '):
return line + ' pass'
elif line.startswith(('if ', 'elif ', 'for ', 'while ')):
return line + ' pass'
else:
return line | def normalize_multiline(line) | Normalize multiline-related code that will cause syntax error.
This is for purposes of checking syntax. | 3.004452 | 2.876445 | 1.044502 |
# Replace escaped newlines too
left = line[:offset].rstrip('\n\r \t\\')
right = line[offset:].lstrip('\n\r \t\\')
if right.startswith('#'):
return line
else:
return left + replacement + right | def fix_whitespace(line, offset, replacement) | Replace whitespace at offset and return fixed line. | 4.091779 | 4.262425 | 0.959965 |
# Transform everything to line feed. Then change them back to original
# before returning fixed source code.
original_newline = find_newline(source_lines)
tmp_source = ''.join(normalize_line_endings(source_lines, '\n'))
# Keep a history to break out of cycles.
previous_hashes = set()
if options.line_range:
# Disable "apply_local_fixes()" for now due to issue #175.
fixed_source = tmp_source
else:
# Apply global fixes only once (for efficiency).
fixed_source = apply_global_fixes(tmp_source,
options,
filename=filename)
passes = 0
long_line_ignore_cache = set()
while hash(fixed_source) not in previous_hashes:
if options.pep8_passes >= 0 and passes > options.pep8_passes:
break
passes += 1
previous_hashes.add(hash(fixed_source))
tmp_source = copy.copy(fixed_source)
fix = FixPEP8(
filename,
options,
contents=tmp_source,
long_line_ignore_cache=long_line_ignore_cache)
fixed_source = fix.fix()
sio = io.StringIO(fixed_source)
return ''.join(normalize_line_endings(sio.readlines(), original_newline)) | def fix_lines(source_lines, options, filename='') | Return fixed source code. | 5.02878 | 4.853831 | 1.036043 |
if any(code_match(code, select=options.select, ignore=options.ignore)
for code in ['E101', 'E111']):
source = reindent(source,
indent_size=options.indent_size)
for (code, function) in global_fixes():
if code_match(code, select=options.select, ignore=options.ignore):
if options.verbose:
print('---> Applying {0} fix for {1}'.format(where,
code.upper()),
file=sys.stderr)
source = function(source,
aggressive=options.aggressive)
source = fix_2to3(source,
aggressive=options.aggressive,
select=options.select,
ignore=options.ignore,
filename=filename)
return source | def apply_global_fixes(source, options, where='global', filename='') | Run global fixes on source code.
These are fixes that only need be done once (unlike those in
FixPEP8, which are dependent on pycodestyle). | 3.794862 | 3.702157 | 1.025041 |
parser = create_parser()
args = parser.parse_args(arguments)
if not args.files and not args.list_fixes:
parser.error('incorrect number of arguments')
args.files = [decode_filename(name) for name in args.files]
if apply_config:
parser = read_config(args, parser)
args = parser.parse_args(arguments)
args.files = [decode_filename(name) for name in args.files]
if '-' in args.files:
if len(args.files) > 1:
parser.error('cannot mix stdin and regular files')
if args.diff:
parser.error('--diff cannot be used with standard input')
if args.in_place:
parser.error('--in-place cannot be used with standard input')
if args.recursive:
parser.error('--recursive cannot be used with standard input')
if len(args.files) > 1 and not (args.in_place or args.diff):
parser.error('autopep8 only takes one filename as argument '
'unless the "--in-place" or "--diff" args are '
'used')
if args.recursive and not (args.in_place or args.diff):
parser.error('--recursive must be used with --in-place or --diff')
if args.in_place and args.diff:
parser.error('--in-place and --diff are mutually exclusive')
if args.max_line_length <= 0:
parser.error('--max-line-length must be greater than 0')
if args.select:
args.select = _split_comma_separated(args.select)
if args.ignore:
args.ignore = _split_comma_separated(args.ignore)
elif not args.select:
if args.aggressive:
# Enable everything by default if aggressive.
args.select = set(['E', 'W'])
else:
args.ignore = _split_comma_separated(DEFAULT_IGNORE)
if args.exclude:
args.exclude = _split_comma_separated(args.exclude)
else:
args.exclude = set([])
if args.jobs < 1:
# Do not import multiprocessing globally in case it is not supported
# on the platform.
import multiprocessing
args.jobs = multiprocessing.cpu_count()
if args.jobs > 1 and not args.in_place:
parser.error('parallel jobs requires --in-place')
if args.line_range:
if args.line_range[0] <= 0:
parser.error('--range must be positive numbers')
if args.line_range[0] > args.line_range[1]:
parser.error('First value of --range should be less than or equal '
'to the second')
return args | def parse_args(arguments, apply_config=False) | Parse command-line options. | 2.407492 | 2.386768 | 1.008683 |
if parameters[1].verbose:
print('[file:{0}]'.format(parameters[0]), file=sys.stderr)
try:
fix_file(*parameters)
except IOError as error:
print(unicode(error), file=sys.stderr) | def _fix_file(parameters) | Helper function for optionally running fix_file() in parallel. | 5.024316 | 4.468358 | 1.124421 |
filenames = find_files(filenames, options.recursive, options.exclude)
if options.jobs > 1:
import multiprocessing
pool = multiprocessing.Pool(options.jobs)
pool.map(_fix_file,
[(name, options) for name in filenames])
else:
for name in filenames:
_fix_file((name, options, output)) | def fix_multiple_files(filenames, options, output=None) | Fix list of files.
Optionally fix files recursively. | 2.661638 | 3.181854 | 0.836505 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.