这似乎工作正常 -
%time a = "abc"
print(a)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 19.1 µs
abc
这不是 -
def func():
%time b = "abc"
print(b)
func()
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 31 µs
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-57f7d48952b8> in <module>()
3 print(b)
4
----> 5 func()
<ipython-input-8-57f7d48952b8> in func()
1 def func():
2 get_ipython().magic(u'time b = "abc"')
----> 3 print(b)
4
5 func()
NameError: global name 'b' is not defined
这是指向notebook
的链接我使用的是python 2.7,但尚未尝试使用python3。
这是预期的行为吗?
答案 0 :(得分:1)
我几乎可以肯定这是一个IPython错误。 Reported here
In [31]: def func():
...: a = 2
...: %time b = 1
...: print(locals())
...: print a
...: print b
In [32]: func()
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 6.2 µs
{'a': 2, 'b': 1}
2
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-32-08a2da4138f6> in <module>()
----> 1 func()
<ipython-input-31-13da62c18a7e> in func()
4 print(locals())
5 print a
----> 6 print b
7
8
NameError: global name 'b' is not defined
答案 1 :(得分:1)
如果你在等号之后写%time
,它可以在Python 3中运行,如下所示:
def func():
a = 2
b = %time 1
print(locals())
print(a)
print(b)
func()
输出:
CPU times: user 6 µs, sys: 0 ns, total: 6 µs
Wall time: 10.3 µs
{'a': 2, 'b': 1}
2
1