thefalcon avatar thefalcon committed 79330be

Make it work with Python 3.x.

Comments (0)

Files changed (4)

_line_profiler.pyx

         """ Record line profiling information for the given Python function.
         """
         try:
-            code = func.func_code
+            code = func.__code__
         except AttributeError:
             import warnings
-            warnings.warn("Could not extract a code object for the object %r" % (func,))
+            warnings.warn("Could not extract a code object for the object %s" % (func + " "))
             return
         if code not in self.code_map:
             self.code_map[code] = {}
     if sys.version_info[:2] >= (2,5):
         # Delay compilation because the syntax is not compatible with older
         # Python versions.
-        exec pep342_gen_wrapper
+        exec(pep342_gen_wrapper)
     else:
         def wrap_generator(self, func):
             """ Wrap a generator to profile it.
         if os.path.isfile(fn):
             return fn
 
-    print >>sys.stderr, 'Could not find script %s' % script_name
+    print ('Could not find script %s' % script_name, file=sys.stderr)
     raise SystemExit(1)
 
 def main(args):
     else:
         prof = ContextualProfile()
     if options.builtin:
-        import __builtin__
-        __builtin__.__dict__['profile'] = prof
+        import builtins
+        builtins.__dict__['profile'] = prof
 
     script_file = find_script(sys.argv[0])
     __file__ = script_file
         try:
             ns = locals()
             if options.builtin:
-                execfile(script_file, ns, ns)
+                exec(compile(open(script_file).read(), script_file, 'exec'), ns, ns)
             else:
                 prof.runctx('execfile(%r)' % (script_file,), ns, ns)
         except (KeyboardInterrupt, SystemExit):
             pass
     finally:
         prof.dump_stats(options.outfile)
-        print 'Wrote profile results to %s' % options.outfile
+        print('Wrote profile results to %s' % options.outfile)
         if options.view:
             prof.print_stats()
 
 #!/usr/bin/env python
 # -*- coding: UTF-8 -*-
 
-import cPickle
-from cStringIO import StringIO
+import pickle
+from io import StringIO
 import inspect
 import linecache
 import optparse
 def is_generator(f):
     """ Return True if a function is a generator.
     """
-    isgen = (f.func_code.co_flags & CO_GENERATOR) != 0 
+    isgen = (f.__code__.co_flags & CO_GENERATOR) != 0 
     return isgen
 
 # Code to exec inside of LineProfiler.__call__ to support PEP-342-style
     if sys.version_info[:2] >= (2,5):
         # Delay compilation because the syntax is not compatible with older
         # Python versions.
-        exec pep342_gen_wrapper
+        exec (pep342_gen_wrapper)
     else:
         def wrap_generator(self, func):
             """ Wrap a generator to profile it.
         lstats = self.get_stats()
         f = open(filename, 'wb')
         try:
-            cPickle.dump(lstats, f, cPickle.HIGHEST_PROTOCOL)
+            pickle.dump(lstats, f, pickle.HIGHEST_PROTOCOL)
         finally:
             f.close()
 
         """
         self.enable_by_count()
         try:
-            exec cmd in globals, locals
+            exec(cmd, globals, locals)
         finally:
             self.disable_by_count()
         return self
     """
     if stream is None:
         stream = sys.stdout
-    print >>stream, "File: %s" % filename
-    print >>stream, "Function: %s at line %s" % (func_name, start_lineno)
+    print("File: %s" % filename, file=stream)
+    print("Function: %s at line %s" % (func_name, start_lineno), file=stream)
     template = '%6s %9s %12s %8s %8s  %-s'
     d = {}
     total_time = 0.0
     for lineno, nhits, time in timings:
         total_time += time
         linenos.append(lineno)
-    print >>stream, "Total time: %g s" % (total_time * unit)
+    print("Total time: %g s" % (total_time * unit), file=stream)
     if not os.path.exists(filename):
-        print >>stream, ""
-        print >>stream, "Could not find file %s" % filename
-        print >>stream, "Are you sure you are running this program from the same directory"
-        print >>stream, "that you ran the profiler from?"
-        print >>stream, "Continuing without the function's contents."
+        print("", file=stream)
+        print("Could not find file %s" % filename, file=stream)
+        print("Are you sure you are running this program from the same directory", file=stream)
+        print("that you ran the profiler from?", file=stream)
+        print("Continuing without the function's contents.", file=stream)
         # Fake empty lines so we can see the timings, if not the code.
         nlines = max(linenos) - min(min(linenos), start_lineno) + 1
         sublines = [''] * nlines
     empty = ('', '', '', '')
     header = template % ('Line #', 'Hits', 'Time', 'Per Hit', '% Time', 
         'Line Contents')
-    print >>stream, ""
-    print >>stream, header
-    print >>stream, '=' * len(header)
+    print("", file=stream)
+    print(header, file=stream)
+    print('=' * len(header), file=stream)
     for lineno, line in zip(linenos, sublines):
         nhits, time, per_hit, percent = d.get(lineno, empty)
-        print >>stream, template % (lineno, nhits, time, per_hit, percent,
-            line.rstrip('\n').rstrip('\r'))
-    print >>stream, ""
+        print(template % (lineno, nhits, time, per_hit, percent,
+            line.rstrip('\n').rstrip('\r')), file=stream)
+    print("", file=stream)
 
 def show_text(stats, unit, stream=None):
     """ Show text for the given timings.
     """
     if stream is None:
         stream = sys.stdout
-    print >>stream, 'Timer unit: %g s' % unit
-    print >>stream, ''
+    print('Timer unit: %g s' % unit, file=stream)
+    print('', file=stream)
     for (fn, lineno, name), timings in sorted(stats.items()):
         show_func(fn, lineno, name, stats[fn, lineno, name], unit, stream=stream)
 
     for name in opts.f:
         try:
             funcs.append(eval(name, global_ns, local_ns))
-        except Exception, e:
+        except Exception as e:
             raise UsageError('Could not find function %r.\n%s: %s' % (name, 
                 e.__class__.__name__, e))
 
         page(output, screen_lines=self.shell.rc.screen_length)
     else:
         page(output)
-    print message,
+    print(message, end=' ')
 
     dump_file = opts.D[0]
     if dump_file:
         profile.dump_stats(dump_file)
-        print '\n*** Profile stats pickled to file',\
-              `dump_file`+'.',message
+        print('\n*** Profile stats pickled to file',\
+            dump_file + '.' , message)
 
     text_file = opts.T[0]
     if text_file:
         pfile = open(text_file, 'w')
         pfile.write(output)
         pfile.close()
-        print '\n*** Profile printout saved to text file',\
-              `text_file`+'.',message
+        print('\n*** Profile printout saved to text file',\
+            text_file + '.', message)
 
     return_value = None
     if opts.has_key('r'):
     """
     f = open(filename, 'rb')
     try:
-        lstats = cPickle.load(f)
+        lstats = pickle.load(f)
     finally:
         f.close()
     return lstats
     from Cython.Distutils import build_ext
     cmdclass = dict(build_ext=build_ext)
     line_profiler_source = '_line_profiler.pyx'
-except ImportError, e:
+except ImportError as e:
     cmdclass = {}
     line_profiler_source = '_line_profiler.c'
     if not os.path.exists(line_profiler_source):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.