execution.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. # -*- coding: utf-8 -*-
  2. """Implementation of execution-related magic functions."""
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from __future__ import print_function
  6. from __future__ import absolute_import
  7. import ast
  8. import bdb
  9. import gc
  10. import itertools
  11. import os
  12. import sys
  13. import time
  14. import timeit
  15. from pdb import Restart
  16. # cProfile was added in Python2.5
  17. try:
  18. import cProfile as profile
  19. import pstats
  20. except ImportError:
  21. # profile isn't bundled by default in Debian for license reasons
  22. try:
  23. import profile, pstats
  24. except ImportError:
  25. profile = pstats = None
  26. from IPython.core import oinspect
  27. from IPython.core import magic_arguments
  28. from IPython.core import page
  29. from IPython.core.error import UsageError
  30. from IPython.core.macro import Macro
  31. from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
  32. line_cell_magic, on_off, needs_local_scope)
  33. from IPython.testing.skipdoctest import skip_doctest
  34. from IPython.utils import py3compat
  35. from IPython.utils.py3compat import builtin_mod, iteritems, PY3
  36. from IPython.utils.contexts import preserve_keys
  37. from IPython.utils.capture import capture_output
  38. from IPython.utils.ipstruct import Struct
  39. from IPython.utils.module_paths import find_mod
  40. from IPython.utils.path import get_py_filename, shellglob
  41. from IPython.utils.timing import clock, clock2
  42. from warnings import warn
  43. from logging import error
  44. if PY3:
  45. from io import StringIO
  46. else:
  47. from StringIO import StringIO
  48. #-----------------------------------------------------------------------------
  49. # Magic implementation classes
  50. #-----------------------------------------------------------------------------
  51. class TimeitResult(object):
  52. """
  53. Object returned by the timeit magic with info about the run.
  54. Contains the following attributes :
  55. loops: (int) number of loops done per measurement
  56. repeat: (int) number of times the measurement has been repeated
  57. best: (float) best execution time / number
  58. all_runs: (list of float) execution time of each run (in s)
  59. compile_time: (float) time of statement compilation (s)
  60. """
  61. def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
  62. self.loops = loops
  63. self.repeat = repeat
  64. self.best = best
  65. self.worst = worst
  66. self.all_runs = all_runs
  67. self.compile_time = compile_time
  68. self._precision = precision
  69. def _repr_pretty_(self, p , cycle):
  70. if self.loops == 1: # No s at "loops" if only one loop
  71. unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
  72. _format_time(self.best, self._precision))
  73. else:
  74. unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
  75. _format_time(self.best, self._precision))
  76. p.text(u'<TimeitResult : '+unic+u'>')
  77. class TimeitTemplateFiller(ast.NodeTransformer):
  78. """Fill in the AST template for timing execution.
  79. This is quite closely tied to the template definition, which is in
  80. :meth:`ExecutionMagics.timeit`.
  81. """
  82. def __init__(self, ast_setup, ast_stmt):
  83. self.ast_setup = ast_setup
  84. self.ast_stmt = ast_stmt
  85. def visit_FunctionDef(self, node):
  86. "Fill in the setup statement"
  87. self.generic_visit(node)
  88. if node.name == "inner":
  89. node.body[:1] = self.ast_setup.body
  90. return node
  91. def visit_For(self, node):
  92. "Fill in the statement to be timed"
  93. if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
  94. node.body = self.ast_stmt.body
  95. return node
  96. class Timer(timeit.Timer):
  97. """Timer class that explicitly uses self.inner
  98. which is an undocumented implementation detail of CPython,
  99. not shared by PyPy.
  100. """
  101. # Timer.timeit copied from CPython 3.4.2
  102. def timeit(self, number=timeit.default_number):
  103. """Time 'number' executions of the main statement.
  104. To be precise, this executes the setup statement once, and
  105. then returns the time it takes to execute the main statement
  106. a number of times, as a float measured in seconds. The
  107. argument is the number of times through the loop, defaulting
  108. to one million. The main statement, the setup statement and
  109. the timer function to be used are passed to the constructor.
  110. """
  111. it = itertools.repeat(None, number)
  112. gcold = gc.isenabled()
  113. gc.disable()
  114. try:
  115. timing = self.inner(it, self.timer)
  116. finally:
  117. if gcold:
  118. gc.enable()
  119. return timing
  120. @magics_class
  121. class ExecutionMagics(Magics):
  122. """Magics related to code execution, debugging, profiling, etc.
  123. """
  124. def __init__(self, shell):
  125. super(ExecutionMagics, self).__init__(shell)
  126. if profile is None:
  127. self.prun = self.profile_missing_notice
  128. # Default execution function used to actually run user code.
  129. self.default_runner = None
  130. def profile_missing_notice(self, *args, **kwargs):
  131. error("""\
  132. The profile module could not be found. It has been removed from the standard
  133. python packages because of its non-free license. To use profiling, install the
  134. python-profiler package from non-free.""")
  135. @skip_doctest
  136. @line_cell_magic
  137. def prun(self, parameter_s='', cell=None):
  138. """Run a statement through the python code profiler.
  139. Usage, in line mode:
  140. %prun [options] statement
  141. Usage, in cell mode:
  142. %%prun [options] [statement]
  143. code...
  144. code...
  145. In cell mode, the additional code lines are appended to the (possibly
  146. empty) statement in the first line. Cell mode allows you to easily
  147. profile multiline blocks without having to put them in a separate
  148. function.
  149. The given statement (which doesn't require quote marks) is run via the
  150. python profiler in a manner similar to the profile.run() function.
  151. Namespaces are internally managed to work correctly; profile.run
  152. cannot be used in IPython because it makes certain assumptions about
  153. namespaces which do not hold under IPython.
  154. Options:
  155. -l <limit>
  156. you can place restrictions on what or how much of the
  157. profile gets printed. The limit value can be:
  158. * A string: only information for function names containing this string
  159. is printed.
  160. * An integer: only these many lines are printed.
  161. * A float (between 0 and 1): this fraction of the report is printed
  162. (for example, use a limit of 0.4 to see the topmost 40% only).
  163. You can combine several limits with repeated use of the option. For
  164. example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
  165. information about class constructors.
  166. -r
  167. return the pstats.Stats object generated by the profiling. This
  168. object has all the information about the profile in it, and you can
  169. later use it for further analysis or in other functions.
  170. -s <key>
  171. sort profile by given key. You can provide more than one key
  172. by using the option several times: '-s key1 -s key2 -s key3...'. The
  173. default sorting key is 'time'.
  174. The following is copied verbatim from the profile documentation
  175. referenced below:
  176. When more than one key is provided, additional keys are used as
  177. secondary criteria when the there is equality in all keys selected
  178. before them.
  179. Abbreviations can be used for any key names, as long as the
  180. abbreviation is unambiguous. The following are the keys currently
  181. defined:
  182. ============ =====================
  183. Valid Arg Meaning
  184. ============ =====================
  185. "calls" call count
  186. "cumulative" cumulative time
  187. "file" file name
  188. "module" file name
  189. "pcalls" primitive call count
  190. "line" line number
  191. "name" function name
  192. "nfl" name/file/line
  193. "stdname" standard name
  194. "time" internal time
  195. ============ =====================
  196. Note that all sorts on statistics are in descending order (placing
  197. most time consuming items first), where as name, file, and line number
  198. searches are in ascending order (i.e., alphabetical). The subtle
  199. distinction between "nfl" and "stdname" is that the standard name is a
  200. sort of the name as printed, which means that the embedded line
  201. numbers get compared in an odd way. For example, lines 3, 20, and 40
  202. would (if the file names were the same) appear in the string order
  203. "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
  204. line numbers. In fact, sort_stats("nfl") is the same as
  205. sort_stats("name", "file", "line").
  206. -T <filename>
  207. save profile results as shown on screen to a text
  208. file. The profile is still shown on screen.
  209. -D <filename>
  210. save (via dump_stats) profile statistics to given
  211. filename. This data is in a format understood by the pstats module, and
  212. is generated by a call to the dump_stats() method of profile
  213. objects. The profile is still shown on screen.
  214. -q
  215. suppress output to the pager. Best used with -T and/or -D above.
  216. If you want to run complete programs under the profiler's control, use
  217. ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
  218. contains profiler specific options as described here.
  219. You can read the complete documentation for the profile module with::
  220. In [1]: import profile; profile.help()
  221. """
  222. opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
  223. list_all=True, posix=False)
  224. if cell is not None:
  225. arg_str += '\n' + cell
  226. arg_str = self.shell.input_splitter.transform_cell(arg_str)
  227. return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
  228. def _run_with_profiler(self, code, opts, namespace):
  229. """
  230. Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
  231. Parameters
  232. ----------
  233. code : str
  234. Code to be executed.
  235. opts : Struct
  236. Options parsed by `self.parse_options`.
  237. namespace : dict
  238. A dictionary for Python namespace (e.g., `self.shell.user_ns`).
  239. """
  240. # Fill default values for unspecified options:
  241. opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
  242. prof = profile.Profile()
  243. try:
  244. prof = prof.runctx(code, namespace, namespace)
  245. sys_exit = ''
  246. except SystemExit:
  247. sys_exit = """*** SystemExit exception caught in code being profiled."""
  248. stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
  249. lims = opts.l
  250. if lims:
  251. lims = [] # rebuild lims with ints/floats/strings
  252. for lim in opts.l:
  253. try:
  254. lims.append(int(lim))
  255. except ValueError:
  256. try:
  257. lims.append(float(lim))
  258. except ValueError:
  259. lims.append(lim)
  260. # Trap output.
  261. stdout_trap = StringIO()
  262. stats_stream = stats.stream
  263. try:
  264. stats.stream = stdout_trap
  265. stats.print_stats(*lims)
  266. finally:
  267. stats.stream = stats_stream
  268. output = stdout_trap.getvalue()
  269. output = output.rstrip()
  270. if 'q' not in opts:
  271. page.page(output)
  272. print(sys_exit, end=' ')
  273. dump_file = opts.D[0]
  274. text_file = opts.T[0]
  275. if dump_file:
  276. prof.dump_stats(dump_file)
  277. print('\n*** Profile stats marshalled to file',\
  278. repr(dump_file)+'.',sys_exit)
  279. if text_file:
  280. pfile = open(text_file,'w')
  281. pfile.write(output)
  282. pfile.close()
  283. print('\n*** Profile printout saved to text file',\
  284. repr(text_file)+'.',sys_exit)
  285. if 'r' in opts:
  286. return stats
  287. else:
  288. return None
  289. @line_magic
  290. def pdb(self, parameter_s=''):
  291. """Control the automatic calling of the pdb interactive debugger.
  292. Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
  293. argument it works as a toggle.
  294. When an exception is triggered, IPython can optionally call the
  295. interactive pdb debugger after the traceback printout. %pdb toggles
  296. this feature on and off.
  297. The initial state of this feature is set in your configuration
  298. file (the option is ``InteractiveShell.pdb``).
  299. If you want to just activate the debugger AFTER an exception has fired,
  300. without having to type '%pdb on' and rerunning your code, you can use
  301. the %debug magic."""
  302. par = parameter_s.strip().lower()
  303. if par:
  304. try:
  305. new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
  306. except KeyError:
  307. print ('Incorrect argument. Use on/1, off/0, '
  308. 'or nothing for a toggle.')
  309. return
  310. else:
  311. # toggle
  312. new_pdb = not self.shell.call_pdb
  313. # set on the shell
  314. self.shell.call_pdb = new_pdb
  315. print('Automatic pdb calling has been turned',on_off(new_pdb))
  316. @skip_doctest
  317. @magic_arguments.magic_arguments()
  318. @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
  319. help="""
  320. Set break point at LINE in FILE.
  321. """
  322. )
  323. @magic_arguments.argument('statement', nargs='*',
  324. help="""
  325. Code to run in debugger.
  326. You can omit this in cell magic mode.
  327. """
  328. )
  329. @line_cell_magic
  330. def debug(self, line='', cell=None):
  331. """Activate the interactive debugger.
  332. This magic command support two ways of activating debugger.
  333. One is to activate debugger before executing code. This way, you
  334. can set a break point, to step through the code from the point.
  335. You can use this mode by giving statements to execute and optionally
  336. a breakpoint.
  337. The other one is to activate debugger in post-mortem mode. You can
  338. activate this mode simply running %debug without any argument.
  339. If an exception has just occurred, this lets you inspect its stack
  340. frames interactively. Note that this will always work only on the last
  341. traceback that occurred, so you must call this quickly after an
  342. exception that you wish to inspect has fired, because if another one
  343. occurs, it clobbers the previous one.
  344. If you want IPython to automatically do this on every exception, see
  345. the %pdb magic for more details.
  346. """
  347. args = magic_arguments.parse_argstring(self.debug, line)
  348. if not (args.breakpoint or args.statement or cell):
  349. self._debug_post_mortem()
  350. else:
  351. code = "\n".join(args.statement)
  352. if cell:
  353. code += "\n" + cell
  354. self._debug_exec(code, args.breakpoint)
  355. def _debug_post_mortem(self):
  356. self.shell.debugger(force=True)
  357. def _debug_exec(self, code, breakpoint):
  358. if breakpoint:
  359. (filename, bp_line) = breakpoint.split(':', 1)
  360. bp_line = int(bp_line)
  361. else:
  362. (filename, bp_line) = (None, None)
  363. self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
  364. @line_magic
  365. def tb(self, s):
  366. """Print the last traceback with the currently active exception mode.
  367. See %xmode for changing exception reporting modes."""
  368. self.shell.showtraceback()
  369. @skip_doctest
  370. @line_magic
  371. def run(self, parameter_s='', runner=None,
  372. file_finder=get_py_filename):
  373. """Run the named file inside IPython as a program.
  374. Usage::
  375. %run [-n -i -e -G]
  376. [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
  377. ( -m mod | file ) [args]
  378. Parameters after the filename are passed as command-line arguments to
  379. the program (put in sys.argv). Then, control returns to IPython's
  380. prompt.
  381. This is similar to running at a system prompt ``python file args``,
  382. but with the advantage of giving you IPython's tracebacks, and of
  383. loading all variables into your interactive namespace for further use
  384. (unless -p is used, see below).
  385. The file is executed in a namespace initially consisting only of
  386. ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
  387. sees its environment as if it were being run as a stand-alone program
  388. (except for sharing global objects such as previously imported
  389. modules). But after execution, the IPython interactive namespace gets
  390. updated with all variables defined in the program (except for __name__
  391. and sys.argv). This allows for very convenient loading of code for
  392. interactive work, while giving each program a 'clean sheet' to run in.
  393. Arguments are expanded using shell-like glob match. Patterns
  394. '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
  395. tilde '~' will be expanded into user's home directory. Unlike
  396. real shells, quotation does not suppress expansions. Use
  397. *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
  398. To completely disable these expansions, you can use -G flag.
  399. Options:
  400. -n
  401. __name__ is NOT set to '__main__', but to the running file's name
  402. without extension (as python does under import). This allows running
  403. scripts and reloading the definitions in them without calling code
  404. protected by an ``if __name__ == "__main__"`` clause.
  405. -i
  406. run the file in IPython's namespace instead of an empty one. This
  407. is useful if you are experimenting with code written in a text editor
  408. which depends on variables defined interactively.
  409. -e
  410. ignore sys.exit() calls or SystemExit exceptions in the script
  411. being run. This is particularly useful if IPython is being used to
  412. run unittests, which always exit with a sys.exit() call. In such
  413. cases you are interested in the output of the test results, not in
  414. seeing a traceback of the unittest module.
  415. -t
  416. print timing information at the end of the run. IPython will give
  417. you an estimated CPU time consumption for your script, which under
  418. Unix uses the resource module to avoid the wraparound problems of
  419. time.clock(). Under Unix, an estimate of time spent on system tasks
  420. is also given (for Windows platforms this is reported as 0.0).
  421. If -t is given, an additional ``-N<N>`` option can be given, where <N>
  422. must be an integer indicating how many times you want the script to
  423. run. The final timing report will include total and per run results.
  424. For example (testing the script uniq_stable.py)::
  425. In [1]: run -t uniq_stable
  426. IPython CPU timings (estimated):
  427. User : 0.19597 s.
  428. System: 0.0 s.
  429. In [2]: run -t -N5 uniq_stable
  430. IPython CPU timings (estimated):
  431. Total runs performed: 5
  432. Times : Total Per run
  433. User : 0.910862 s, 0.1821724 s.
  434. System: 0.0 s, 0.0 s.
  435. -d
  436. run your program under the control of pdb, the Python debugger.
  437. This allows you to execute your program step by step, watch variables,
  438. etc. Internally, what IPython does is similar to calling::
  439. pdb.run('execfile("YOURFILENAME")')
  440. with a breakpoint set on line 1 of your file. You can change the line
  441. number for this automatic breakpoint to be <N> by using the -bN option
  442. (where N must be an integer). For example::
  443. %run -d -b40 myscript
  444. will set the first breakpoint at line 40 in myscript.py. Note that
  445. the first breakpoint must be set on a line which actually does
  446. something (not a comment or docstring) for it to stop execution.
  447. Or you can specify a breakpoint in a different file::
  448. %run -d -b myotherfile.py:20 myscript
  449. When the pdb debugger starts, you will see a (Pdb) prompt. You must
  450. first enter 'c' (without quotes) to start execution up to the first
  451. breakpoint.
  452. Entering 'help' gives information about the use of the debugger. You
  453. can easily see pdb's full documentation with "import pdb;pdb.help()"
  454. at a prompt.
  455. -p
  456. run program under the control of the Python profiler module (which
  457. prints a detailed report of execution times, function calls, etc).
  458. You can pass other options after -p which affect the behavior of the
  459. profiler itself. See the docs for %prun for details.
  460. In this mode, the program's variables do NOT propagate back to the
  461. IPython interactive namespace (because they remain in the namespace
  462. where the profiler executes them).
  463. Internally this triggers a call to %prun, see its documentation for
  464. details on the options available specifically for profiling.
  465. There is one special usage for which the text above doesn't apply:
  466. if the filename ends with .ipy[nb], the file is run as ipython script,
  467. just as if the commands were written on IPython prompt.
  468. -m
  469. specify module name to load instead of script path. Similar to
  470. the -m option for the python interpreter. Use this option last if you
  471. want to combine with other %run options. Unlike the python interpreter
  472. only source modules are allowed no .pyc or .pyo files.
  473. For example::
  474. %run -m example
  475. will run the example module.
  476. -G
  477. disable shell-like glob expansion of arguments.
  478. """
  479. # get arguments and set sys.argv for program to be run.
  480. opts, arg_lst = self.parse_options(parameter_s,
  481. 'nidtN:b:pD:l:rs:T:em:G',
  482. mode='list', list_all=1)
  483. if "m" in opts:
  484. modulename = opts["m"][0]
  485. modpath = find_mod(modulename)
  486. if modpath is None:
  487. warn('%r is not a valid modulename on sys.path'%modulename)
  488. return
  489. arg_lst = [modpath] + arg_lst
  490. try:
  491. filename = file_finder(arg_lst[0])
  492. except IndexError:
  493. warn('you must provide at least a filename.')
  494. print('\n%run:\n', oinspect.getdoc(self.run))
  495. return
  496. except IOError as e:
  497. try:
  498. msg = str(e)
  499. except UnicodeError:
  500. msg = e.message
  501. error(msg)
  502. return
  503. if filename.lower().endswith(('.ipy', '.ipynb')):
  504. with preserve_keys(self.shell.user_ns, '__file__'):
  505. self.shell.user_ns['__file__'] = filename
  506. self.shell.safe_execfile_ipy(filename)
  507. return
  508. # Control the response to exit() calls made by the script being run
  509. exit_ignore = 'e' in opts
  510. # Make sure that the running script gets a proper sys.argv as if it
  511. # were run from a system shell.
  512. save_argv = sys.argv # save it for later restoring
  513. if 'G' in opts:
  514. args = arg_lst[1:]
  515. else:
  516. # tilde and glob expansion
  517. args = shellglob(map(os.path.expanduser, arg_lst[1:]))
  518. sys.argv = [filename] + args # put in the proper filename
  519. # protect sys.argv from potential unicode strings on Python 2:
  520. if not py3compat.PY3:
  521. sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
  522. if 'i' in opts:
  523. # Run in user's interactive namespace
  524. prog_ns = self.shell.user_ns
  525. __name__save = self.shell.user_ns['__name__']
  526. prog_ns['__name__'] = '__main__'
  527. main_mod = self.shell.user_module
  528. # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
  529. # set the __file__ global in the script's namespace
  530. # TK: Is this necessary in interactive mode?
  531. prog_ns['__file__'] = filename
  532. else:
  533. # Run in a fresh, empty namespace
  534. if 'n' in opts:
  535. name = os.path.splitext(os.path.basename(filename))[0]
  536. else:
  537. name = '__main__'
  538. # The shell MUST hold a reference to prog_ns so after %run
  539. # exits, the python deletion mechanism doesn't zero it out
  540. # (leaving dangling references). See interactiveshell for details
  541. main_mod = self.shell.new_main_mod(filename, name)
  542. prog_ns = main_mod.__dict__
  543. # pickle fix. See interactiveshell for an explanation. But we need to
  544. # make sure that, if we overwrite __main__, we replace it at the end
  545. main_mod_name = prog_ns['__name__']
  546. if main_mod_name == '__main__':
  547. restore_main = sys.modules['__main__']
  548. else:
  549. restore_main = False
  550. # This needs to be undone at the end to prevent holding references to
  551. # every single object ever created.
  552. sys.modules[main_mod_name] = main_mod
  553. if 'p' in opts or 'd' in opts:
  554. if 'm' in opts:
  555. code = 'run_module(modulename, prog_ns)'
  556. code_ns = {
  557. 'run_module': self.shell.safe_run_module,
  558. 'prog_ns': prog_ns,
  559. 'modulename': modulename,
  560. }
  561. else:
  562. if 'd' in opts:
  563. # allow exceptions to raise in debug mode
  564. code = 'execfile(filename, prog_ns, raise_exceptions=True)'
  565. else:
  566. code = 'execfile(filename, prog_ns)'
  567. code_ns = {
  568. 'execfile': self.shell.safe_execfile,
  569. 'prog_ns': prog_ns,
  570. 'filename': get_py_filename(filename),
  571. }
  572. try:
  573. stats = None
  574. if 'p' in opts:
  575. stats = self._run_with_profiler(code, opts, code_ns)
  576. else:
  577. if 'd' in opts:
  578. bp_file, bp_line = parse_breakpoint(
  579. opts.get('b', ['1'])[0], filename)
  580. self._run_with_debugger(
  581. code, code_ns, filename, bp_line, bp_file)
  582. else:
  583. if 'm' in opts:
  584. def run():
  585. self.shell.safe_run_module(modulename, prog_ns)
  586. else:
  587. if runner is None:
  588. runner = self.default_runner
  589. if runner is None:
  590. runner = self.shell.safe_execfile
  591. def run():
  592. runner(filename, prog_ns, prog_ns,
  593. exit_ignore=exit_ignore)
  594. if 't' in opts:
  595. # timed execution
  596. try:
  597. nruns = int(opts['N'][0])
  598. if nruns < 1:
  599. error('Number of runs must be >=1')
  600. return
  601. except (KeyError):
  602. nruns = 1
  603. self._run_with_timing(run, nruns)
  604. else:
  605. # regular execution
  606. run()
  607. if 'i' in opts:
  608. self.shell.user_ns['__name__'] = __name__save
  609. else:
  610. # update IPython interactive namespace
  611. # Some forms of read errors on the file may mean the
  612. # __name__ key was never set; using pop we don't have to
  613. # worry about a possible KeyError.
  614. prog_ns.pop('__name__', None)
  615. with preserve_keys(self.shell.user_ns, '__file__'):
  616. self.shell.user_ns.update(prog_ns)
  617. finally:
  618. # It's a bit of a mystery why, but __builtins__ can change from
  619. # being a module to becoming a dict missing some key data after
  620. # %run. As best I can see, this is NOT something IPython is doing
  621. # at all, and similar problems have been reported before:
  622. # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
  623. # Since this seems to be done by the interpreter itself, the best
  624. # we can do is to at least restore __builtins__ for the user on
  625. # exit.
  626. self.shell.user_ns['__builtins__'] = builtin_mod
  627. # Ensure key global structures are restored
  628. sys.argv = save_argv
  629. if restore_main:
  630. sys.modules['__main__'] = restore_main
  631. else:
  632. # Remove from sys.modules the reference to main_mod we'd
  633. # added. Otherwise it will trap references to objects
  634. # contained therein.
  635. del sys.modules[main_mod_name]
  636. return stats
  637. def _run_with_debugger(self, code, code_ns, filename=None,
  638. bp_line=None, bp_file=None):
  639. """
  640. Run `code` in debugger with a break point.
  641. Parameters
  642. ----------
  643. code : str
  644. Code to execute.
  645. code_ns : dict
  646. A namespace in which `code` is executed.
  647. filename : str
  648. `code` is ran as if it is in `filename`.
  649. bp_line : int, optional
  650. Line number of the break point.
  651. bp_file : str, optional
  652. Path to the file in which break point is specified.
  653. `filename` is used if not given.
  654. Raises
  655. ------
  656. UsageError
  657. If the break point given by `bp_line` is not valid.
  658. """
  659. deb = self.shell.InteractiveTB.pdb
  660. if not deb:
  661. self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
  662. deb = self.shell.InteractiveTB.pdb
  663. # reset Breakpoint state, which is moronically kept
  664. # in a class
  665. bdb.Breakpoint.next = 1
  666. bdb.Breakpoint.bplist = {}
  667. bdb.Breakpoint.bpbynumber = [None]
  668. if bp_line is not None:
  669. # Set an initial breakpoint to stop execution
  670. maxtries = 10
  671. bp_file = bp_file or filename
  672. checkline = deb.checkline(bp_file, bp_line)
  673. if not checkline:
  674. for bp in range(bp_line + 1, bp_line + maxtries + 1):
  675. if deb.checkline(bp_file, bp):
  676. break
  677. else:
  678. msg = ("\nI failed to find a valid line to set "
  679. "a breakpoint\n"
  680. "after trying up to line: %s.\n"
  681. "Please set a valid breakpoint manually "
  682. "with the -b option." % bp)
  683. raise UsageError(msg)
  684. # if we find a good linenumber, set the breakpoint
  685. deb.do_break('%s:%s' % (bp_file, bp_line))
  686. if filename:
  687. # Mimic Pdb._runscript(...)
  688. deb._wait_for_mainpyfile = True
  689. deb.mainpyfile = deb.canonic(filename)
  690. # Start file run
  691. print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
  692. try:
  693. if filename:
  694. # save filename so it can be used by methods on the deb object
  695. deb._exec_filename = filename
  696. while True:
  697. try:
  698. deb.run(code, code_ns)
  699. except Restart:
  700. print("Restarting")
  701. if filename:
  702. deb._wait_for_mainpyfile = True
  703. deb.mainpyfile = deb.canonic(filename)
  704. continue
  705. else:
  706. break
  707. except:
  708. etype, value, tb = sys.exc_info()
  709. # Skip three frames in the traceback: the %run one,
  710. # one inside bdb.py, and the command-line typed by the
  711. # user (run by exec in pdb itself).
  712. self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
  713. @staticmethod
  714. def _run_with_timing(run, nruns):
  715. """
  716. Run function `run` and print timing information.
  717. Parameters
  718. ----------
  719. run : callable
  720. Any callable object which takes no argument.
  721. nruns : int
  722. Number of times to execute `run`.
  723. """
  724. twall0 = time.time()
  725. if nruns == 1:
  726. t0 = clock2()
  727. run()
  728. t1 = clock2()
  729. t_usr = t1[0] - t0[0]
  730. t_sys = t1[1] - t0[1]
  731. print("\nIPython CPU timings (estimated):")
  732. print(" User : %10.2f s." % t_usr)
  733. print(" System : %10.2f s." % t_sys)
  734. else:
  735. runs = range(nruns)
  736. t0 = clock2()
  737. for nr in runs:
  738. run()
  739. t1 = clock2()
  740. t_usr = t1[0] - t0[0]
  741. t_sys = t1[1] - t0[1]
  742. print("\nIPython CPU timings (estimated):")
  743. print("Total runs performed:", nruns)
  744. print(" Times : %10s %10s" % ('Total', 'Per run'))
  745. print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
  746. print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
  747. twall1 = time.time()
  748. print("Wall time: %10.2f s." % (twall1 - twall0))
  749. @skip_doctest
  750. @line_cell_magic
  751. def timeit(self, line='', cell=None):
  752. """Time execution of a Python statement or expression
  753. Usage, in line mode:
  754. %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
  755. or in cell mode:
  756. %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  757. code
  758. code...
  759. Time execution of a Python statement or expression using the timeit
  760. module. This function can be used both as a line and cell magic:
  761. - In line mode you can time a single-line statement (though multiple
  762. ones can be chained with using semicolons).
  763. - In cell mode, the statement in the first line is used as setup code
  764. (executed but not timed) and the body of the cell is timed. The cell
  765. body has access to any variables created in the setup code.
  766. Options:
  767. -n<N>: execute the given statement <N> times in a loop. If this value
  768. is not given, a fitting value is chosen.
  769. -r<R>: repeat the loop iteration <R> times and take the best result.
  770. Default: 3
  771. -t: use time.time to measure the time, which is the default on Unix.
  772. This function measures wall time.
  773. -c: use time.clock to measure the time, which is the default on
  774. Windows and measures wall time. On Unix, resource.getrusage is used
  775. instead and returns the CPU user time.
  776. -p<P>: use a precision of <P> digits to display the timing result.
  777. Default: 3
  778. -q: Quiet, do not print result.
  779. -o: return a TimeitResult that can be stored in a variable to inspect
  780. the result in more details.
  781. Examples
  782. --------
  783. ::
  784. In [1]: %timeit pass
  785. 10000000 loops, best of 3: 53.3 ns per loop
  786. In [2]: u = None
  787. In [3]: %timeit u is None
  788. 10000000 loops, best of 3: 184 ns per loop
  789. In [4]: %timeit -r 4 u == None
  790. 1000000 loops, best of 4: 242 ns per loop
  791. In [5]: import time
  792. In [6]: %timeit -n1 time.sleep(2)
  793. 1 loop, best of 3: 2 s per loop
  794. The times reported by %timeit will be slightly higher than those
  795. reported by the timeit.py script when variables are accessed. This is
  796. due to the fact that %timeit executes the statement in the namespace
  797. of the shell, compared with timeit.py, which uses a single setup
  798. statement to import function or create variables. Generally, the bias
  799. does not matter as long as results from timeit.py are not mixed with
  800. those from %timeit."""
  801. opts, stmt = self.parse_options(line,'n:r:tcp:qo',
  802. posix=False, strict=False)
  803. if stmt == "" and cell is None:
  804. return
  805. timefunc = timeit.default_timer
  806. number = int(getattr(opts, "n", 0))
  807. repeat = int(getattr(opts, "r", timeit.default_repeat))
  808. precision = int(getattr(opts, "p", 3))
  809. quiet = 'q' in opts
  810. return_result = 'o' in opts
  811. if hasattr(opts, "t"):
  812. timefunc = time.time
  813. if hasattr(opts, "c"):
  814. timefunc = clock
  815. timer = Timer(timer=timefunc)
  816. # this code has tight coupling to the inner workings of timeit.Timer,
  817. # but is there a better way to achieve that the code stmt has access
  818. # to the shell namespace?
  819. transform = self.shell.input_splitter.transform_cell
  820. if cell is None:
  821. # called as line magic
  822. ast_setup = self.shell.compile.ast_parse("pass")
  823. ast_stmt = self.shell.compile.ast_parse(transform(stmt))
  824. else:
  825. ast_setup = self.shell.compile.ast_parse(transform(stmt))
  826. ast_stmt = self.shell.compile.ast_parse(transform(cell))
  827. ast_setup = self.shell.transform_ast(ast_setup)
  828. ast_stmt = self.shell.transform_ast(ast_stmt)
  829. # This codestring is taken from timeit.template - we fill it in as an
  830. # AST, so that we can apply our AST transformations to the user code
  831. # without affecting the timing code.
  832. timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
  833. ' setup\n'
  834. ' _t0 = _timer()\n'
  835. ' for _i in _it:\n'
  836. ' stmt\n'
  837. ' _t1 = _timer()\n'
  838. ' return _t1 - _t0\n')
  839. timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
  840. timeit_ast = ast.fix_missing_locations(timeit_ast)
  841. # Track compilation time so it can be reported if too long
  842. # Minimum time above which compilation time will be reported
  843. tc_min = 0.1
  844. t0 = clock()
  845. code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
  846. tc = clock()-t0
  847. ns = {}
  848. exec(code, self.shell.user_ns, ns)
  849. timer.inner = ns["inner"]
  850. # This is used to check if there is a huge difference between the
  851. # best and worst timings.
  852. # Issue: https://github.com/ipython/ipython/issues/6471
  853. worst_tuning = 0
  854. if number == 0:
  855. # determine number so that 0.2 <= total time < 2.0
  856. number = 1
  857. for _ in range(1, 10):
  858. time_number = timer.timeit(number)
  859. worst_tuning = max(worst_tuning, time_number / number)
  860. if time_number >= 0.2:
  861. break
  862. number *= 10
  863. all_runs = timer.repeat(repeat, number)
  864. best = min(all_runs) / number
  865. worst = max(all_runs) / number
  866. if worst_tuning:
  867. worst = max(worst, worst_tuning)
  868. if not quiet :
  869. # Check best timing is greater than zero to avoid a
  870. # ZeroDivisionError.
  871. # In cases where the slowest timing is lesser than a micosecond
  872. # we assume that it does not really matter if the fastest
  873. # timing is 4 times faster than the slowest timing or not.
  874. if worst > 4 * best and best > 0 and worst > 1e-6:
  875. print("The slowest run took %0.2f times longer than the "
  876. "fastest. This could mean that an intermediate result "
  877. "is being cached." % (worst / best))
  878. if number == 1: # No s at "loops" if only one loop
  879. print(u"%d loop, best of %d: %s per loop" % (number, repeat,
  880. _format_time(best, precision)))
  881. else:
  882. print(u"%d loops, best of %d: %s per loop" % (number, repeat,
  883. _format_time(best, precision)))
  884. if tc > tc_min:
  885. print("Compiler time: %.2f s" % tc)
  886. if return_result:
  887. return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
  888. @skip_doctest
  889. @needs_local_scope
  890. @line_cell_magic
  891. def time(self,line='', cell=None, local_ns=None):
  892. """Time execution of a Python statement or expression.
  893. The CPU and wall clock times are printed, and the value of the
  894. expression (if any) is returned. Note that under Win32, system time
  895. is always reported as 0, since it can not be measured.
  896. This function can be used both as a line and cell magic:
  897. - In line mode you can time a single-line statement (though multiple
  898. ones can be chained with using semicolons).
  899. - In cell mode, you can time the cell body (a directly
  900. following statement raises an error).
  901. This function provides very basic timing functionality. Use the timeit
  902. magic for more control over the measurement.
  903. Examples
  904. --------
  905. ::
  906. In [1]: %time 2**128
  907. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  908. Wall time: 0.00
  909. Out[1]: 340282366920938463463374607431768211456L
  910. In [2]: n = 1000000
  911. In [3]: %time sum(range(n))
  912. CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
  913. Wall time: 1.37
  914. Out[3]: 499999500000L
  915. In [4]: %time print 'hello world'
  916. hello world
  917. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  918. Wall time: 0.00
  919. Note that the time needed by Python to compile the given expression
  920. will be reported if it is more than 0.1s. In this example, the
  921. actual exponentiation is done by Python at compilation time, so while
  922. the expression can take a noticeable amount of time to compute, that
  923. time is purely due to the compilation:
  924. In [5]: %time 3**9999;
  925. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  926. Wall time: 0.00 s
  927. In [6]: %time 3**999999;
  928. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  929. Wall time: 0.00 s
  930. Compiler : 0.78 s
  931. """
  932. # fail immediately if the given expression can't be compiled
  933. if line and cell:
  934. raise UsageError("Can't use statement directly after '%%time'!")
  935. if cell:
  936. expr = self.shell.input_transformer_manager.transform_cell(cell)
  937. else:
  938. expr = self.shell.input_transformer_manager.transform_cell(line)
  939. # Minimum time above which parse time will be reported
  940. tp_min = 0.1
  941. t0 = clock()
  942. expr_ast = self.shell.compile.ast_parse(expr)
  943. tp = clock()-t0
  944. # Apply AST transformations
  945. expr_ast = self.shell.transform_ast(expr_ast)
  946. # Minimum time above which compilation time will be reported
  947. tc_min = 0.1
  948. if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
  949. mode = 'eval'
  950. source = '<timed eval>'
  951. expr_ast = ast.Expression(expr_ast.body[0].value)
  952. else:
  953. mode = 'exec'
  954. source = '<timed exec>'
  955. t0 = clock()
  956. code = self.shell.compile(expr_ast, source, mode)
  957. tc = clock()-t0
  958. # skew measurement as little as possible
  959. glob = self.shell.user_ns
  960. wtime = time.time
  961. # time execution
  962. wall_st = wtime()
  963. if mode=='eval':
  964. st = clock2()
  965. out = eval(code, glob, local_ns)
  966. end = clock2()
  967. else:
  968. st = clock2()
  969. exec(code, glob, local_ns)
  970. end = clock2()
  971. out = None
  972. wall_end = wtime()
  973. # Compute actual times and report
  974. wall_time = wall_end-wall_st
  975. cpu_user = end[0]-st[0]
  976. cpu_sys = end[1]-st[1]
  977. cpu_tot = cpu_user+cpu_sys
  978. # On windows cpu_sys is always zero, so no new information to the next print
  979. if sys.platform != 'win32':
  980. print("CPU times: user %s, sys: %s, total: %s" % \
  981. (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
  982. print("Wall time: %s" % _format_time(wall_time))
  983. if tc > tc_min:
  984. print("Compiler : %s" % _format_time(tc))
  985. if tp > tp_min:
  986. print("Parser : %s" % _format_time(tp))
  987. return out
  988. @skip_doctest
  989. @line_magic
  990. def macro(self, parameter_s=''):
  991. """Define a macro for future re-execution. It accepts ranges of history,
  992. filenames or string objects.
  993. Usage:\\
  994. %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
  995. Options:
  996. -r: use 'raw' input. By default, the 'processed' history is used,
  997. so that magics are loaded in their transformed version to valid
  998. Python. If this option is given, the raw input as typed at the
  999. command line is used instead.
  1000. -q: quiet macro definition. By default, a tag line is printed
  1001. to indicate the macro has been created, and then the contents of
  1002. the macro are printed. If this option is given, then no printout
  1003. is produced once the macro is created.
  1004. This will define a global variable called `name` which is a string
  1005. made of joining the slices and lines you specify (n1,n2,... numbers
  1006. above) from your input history into a single string. This variable
  1007. acts like an automatic function which re-executes those lines as if
  1008. you had typed them. You just type 'name' at the prompt and the code
  1009. executes.
  1010. The syntax for indicating input ranges is described in %history.
  1011. Note: as a 'hidden' feature, you can also use traditional python slice
  1012. notation, where N:M means numbers N through M-1.
  1013. For example, if your history contains (print using %hist -n )::
  1014. 44: x=1
  1015. 45: y=3
  1016. 46: z=x+y
  1017. 47: print x
  1018. 48: a=5
  1019. 49: print 'x',x,'y',y
  1020. you can create a macro with lines 44 through 47 (included) and line 49
  1021. called my_macro with::
  1022. In [55]: %macro my_macro 44-47 49
  1023. Now, typing `my_macro` (without quotes) will re-execute all this code
  1024. in one pass.
  1025. You don't need to give the line-numbers in order, and any given line
  1026. number can appear multiple times. You can assemble macros with any
  1027. lines from your input history in any order.
  1028. The macro is a simple object which holds its value in an attribute,
  1029. but IPython's display system checks for macros and executes them as
  1030. code instead of printing them when you type their name.
  1031. You can view a macro's contents by explicitly printing it with::
  1032. print macro_name
  1033. """
  1034. opts,args = self.parse_options(parameter_s,'rq',mode='list')
  1035. if not args: # List existing macros
  1036. return sorted(k for k,v in iteritems(self.shell.user_ns) if\
  1037. isinstance(v, Macro))
  1038. if len(args) == 1:
  1039. raise UsageError(
  1040. "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
  1041. name, codefrom = args[0], " ".join(args[1:])
  1042. #print 'rng',ranges # dbg
  1043. try:
  1044. lines = self.shell.find_user_code(codefrom, 'r' in opts)
  1045. except (ValueError, TypeError) as e:
  1046. print(e.args[0])
  1047. return
  1048. macro = Macro(lines)
  1049. self.shell.define_macro(name, macro)
  1050. if not ( 'q' in opts) :
  1051. print('Macro `%s` created. To execute, type its name (without quotes).' % name)
  1052. print('=== Macro contents: ===')
  1053. print(macro, end=' ')
  1054. @magic_arguments.magic_arguments()
  1055. @magic_arguments.argument('output', type=str, default='', nargs='?',
  1056. help="""The name of the variable in which to store output.
  1057. This is a utils.io.CapturedIO object with stdout/err attributes
  1058. for the text of the captured output.
  1059. CapturedOutput also has a show() method for displaying the output,
  1060. and __call__ as well, so you can use that to quickly display the
  1061. output.
  1062. If unspecified, captured output is discarded.
  1063. """
  1064. )
  1065. @magic_arguments.argument('--no-stderr', action="store_true",
  1066. help="""Don't capture stderr."""
  1067. )
  1068. @magic_arguments.argument('--no-stdout', action="store_true",
  1069. help="""Don't capture stdout."""
  1070. )
  1071. @magic_arguments.argument('--no-display', action="store_true",
  1072. help="""Don't capture IPython's rich display."""
  1073. )
  1074. @cell_magic
  1075. def capture(self, line, cell):
  1076. """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
  1077. args = magic_arguments.parse_argstring(self.capture, line)
  1078. out = not args.no_stdout
  1079. err = not args.no_stderr
  1080. disp = not args.no_display
  1081. with capture_output(out, err, disp) as io:
  1082. self.shell.run_cell(cell)
  1083. if args.output:
  1084. self.shell.user_ns[args.output] = io
  1085. def parse_breakpoint(text, current_file):
  1086. '''Returns (file, line) for file:line and (current_file, line) for line'''
  1087. colon = text.find(':')
  1088. if colon == -1:
  1089. return current_file, int(text)
  1090. else:
  1091. return text[:colon], int(text[colon+1:])
  1092. def _format_time(timespan, precision=3):
  1093. """Formats the timespan in a human readable form"""
  1094. import math
  1095. if timespan >= 60.0:
  1096. # we have more than a minute, format that in a human readable form
  1097. # Idea from http://snipplr.com/view/5713/
  1098. parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
  1099. time = []
  1100. leftover = timespan
  1101. for suffix, length in parts:
  1102. value = int(leftover / length)
  1103. if value > 0:
  1104. leftover = leftover % length
  1105. time.append(u'%s%s' % (str(value), suffix))
  1106. if leftover < 1:
  1107. break
  1108. return " ".join(time)
  1109. # Unfortunately the unicode 'micro' symbol can cause problems in
  1110. # certain terminals.
  1111. # See bug: https://bugs.launchpad.net/ipython/+bug/348466
  1112. # Try to prevent crashes by being more secure than it needs to
  1113. # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
  1114. units = [u"s", u"ms",u'us',"ns"] # the save value
  1115. if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
  1116. try:
  1117. u'\xb5'.encode(sys.stdout.encoding)
  1118. units = [u"s", u"ms",u'\xb5s',"ns"]
  1119. except:
  1120. pass
  1121. scaling = [1, 1e3, 1e6, 1e9]
  1122. if timespan > 0.0:
  1123. order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
  1124. else:
  1125. order = 3
  1126. return u"%.*g %s" % (precision, timespan * scaling[order], units[order])