我正在尝试学习如何使用 timeit 来计时由 python 驱动的命令行参数。
from subprocess import *
import timeit
p = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE )
dir_time = timeit.timeit('p.stdin.write("dir\n"),p.stdin.write("exit\n")')
print p.stdout.read()
不幸的是,当我运行它时,我得到
"exceptions.SyntaxError: EOL 扫描字符串文字时(第 6 行,偏移量 26):'p.stdin.write(""dir'"
我见过similar question about EOL syntax error when using timeit and cmd它的解决方案是替换单引号,但是我没有将代码片段直接输入到cmd中,它们的命令中永远不会包含结束行字符,并且双引号会产生语法错误。
有什么方法可以分隔行尾字符但在cmd中仍然有效吗?我是否对 timeit 中的两个参数使用了错误的语法?
最佳答案
要解决 EOL 的直接问题,您可以使用原始字符串文字:r'p.stdin.write("dir\n"),..'
(注意:r ''
) 否则 \n
会被解释为换行符,从而导致您看到的错误:
>>> import timeit
>>> timeit.timeit('"a" + "\n"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/timeit.py", line 230, in timeit
return Timer(stmt, setup, timer).timeit(number)
File "/usr/lib/python2.7/timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 6
"a" + "
^
SyntaxError: EOL while scanning string literal
对比
>>> timeit.timeit(r'"a" + "\n"')
0.021812915802001953
更普遍的问题是:
timeit(r'p.stdin.write("dir\n"),p.stdin.write("exit\n")')
不起作用p
可能无法访问 (NameError
)即使它有效,也不会测量在
cmd.exe
中运行dir
命令所需的时间它将测量将命令写入内部
python
文件缓冲区和/或将其通过管道推送到cmd.exe
所需的时间否则会引发 IOError/OSError
管道可能在第一次执行
exit
后关闭。timeit
多次运行代码(默认为 1000000 次)。
看起来像XY problem 。如果您想知道如何测量在 cmd.exe 中运行内部命令所需的时间,请直接将其作为一个新问题询问。
timeit
在这里不是合适的工具。
关于python - 如何将 timeit 与包含 EOL 字符的命令一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404823/