我正在阅读有关timeit的Python 3.7文档,但是当我尝试Examples部分中的示例时,它会出错(请参见下文):
python -m timeit -s 'text = "sample string"; char = "g"' 'char in text'
我收到以下错误:
Traceback (most recent call last):
File "C:\Users\user\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\user\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\user\Anaconda3\lib\timeit.py", line 374, in <module>
sys.exit(main())
File "C:\Users\user\Anaconda3\lib\timeit.py", line 313, in main
t = Timer(stmt, setup, timer)
File "C:\Users\user\Anaconda3\lib\timeit.py", line 109, in __init__
compile(setup, dummy_src_name, "exec")
File "<timeit-src>", line 1
'text
^
SyntaxError: EOL while scanning string literal
我正在Windows 7上运行Python 3.7.3。(我也在Window 10上对其进行了测试:cmd和powershell)
为什么我会收到该错误?
编辑:当我在msys2或Linux上执行该命令时,以上命令可以正常工作。
答案 0 :(得分:0)
只是引用问题。同样的问题在这里:
python -m timeit -s 'text = "sample string"; char = "g"' 'char in text'
Traceback (most recent call last):
File "C:\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Python37\lib\timeit.py", line 374, in <module>
sys.exit(main())
File "C:\Python37\lib\timeit.py", line 313, in main
t = Timer(stmt, setup, timer)
File "C:\Python37\lib\timeit.py", line 109, in __init__
compile(setup, dummy_src_name, "exec")
File "<timeit-src>", line 1
'text
^
SyntaxError: EOL while scanning string literal
将其更改为:
python -m timeit -s "text = 'sample string'; char = 'g' 'char in text'"
20000000 loops, best of 5: 8.62 nsec per loop
答案 1 :(得分:0)
我只是在本地运行您的代码而没有问题:
> python -m timeit -s 'text = "sample string"; char = "g"' 'char in text'
10000000 loops, best of 5: 31.6 nsec per loop
鉴于您的错误消息的这一部分:'text
,我猜测当您尝试运行命令时,您没有在'char in text'
末尾得到最后的单引号。