Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Update custom stringifier example with a method to use sub-second timeout #21

Merged
merged 2 commits into from

2 participants

@asmeurer
Collaborator

The trick is to use signal.setitimer instead of signal.alarm (see http://docs.python.org/library/signal.html#signal.setitimer), which unfortunately only exists in Python 2.6+.

@inducer inducer merged commit d73bbc2 into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 16 additions and 5 deletions.
  1. +16 −5 example-stringifier.py
View
21 example-stringifier.py
@@ -23,8 +23,9 @@
PuDB), and add the path to the file in the "Custom" field under the "Variable
Stringifier" heading.
-The example in this file returns the string value, unless it take more than a
-second to compute, in which case it falls back to the type.
+The example in this file returns the string value, unless it take more than 500
+ms (1 second in Python 2.5-) to compute, in which case it falls back to the
+type.
TIP: Run "python -m pudb.run example-stringifier.py and set this file to be
your stringifier in the settings to see how it works.
@@ -39,6 +40,8 @@
"""
import time
import signal
+import sys
+import math
class TimeOutError(Exception):
pass
@@ -50,11 +53,19 @@ def run_with_timeout(code, time, globals=None):
"""
Evaluate ``code``, timing out after ``time`` seconds.
- ``time`` must be an integer. The return value is whatever ``code`` returns.
+ In Python 2.5 and lower, ``time`` is rounded up to the nearest integer.
+ The return value is whatever ``code`` returns.
"""
# Set the signal handler and a ``time``-second alarm
signal.signal(signal.SIGALRM, lambda s, f: timeout(s, f, time))
- signal.alarm(time)
+ if sys.version_info > (2, 5):
+ signal.setitimer(signal.ITIMER_REAL, time)
+ else:
+ # The above only exists in Python 2.6+
+ # Otherwise, we have to use this, which only supports integer arguments
+ # Use math.ceil to round a float up.
+ time = int(math.ceil(time))
+ signal.alarm(time)
r = eval(code, globals)
signal.alarm(0) # Disable the alarm
return r
@@ -67,7 +78,7 @@ def pudb_stringifier(obj):
in which case it falls back to type(obj).
"""
try:
- return run_with_timeout("str(obj)", 1, {'obj':obj})
+ return run_with_timeout("str(obj)", 0.5, {'obj':obj})
except TimeOutError:
return (type(obj), "(str too slow to compute)")
Something went wrong with that request. Please try again.