【问题标题】:How can you use timeit with commands containing EOL characters?如何将 timeit 与包含 EOL 字符的命令一起使用?
【发布时间】:2015-04-02 04:08:10
【问题描述】:

我正在尝试学习如何使用 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 while scanning string literal (line 6, offset 26): 'p.stdin.write(""dir'"

我见过similar question about EOL syntax error when using timeit and cmd,它的解决方案是替换单引号,但是我没有将代码 sn-ps 直接输入 cmd,它们的命令中从不包含结束行字符,双引号会产生语法错误.

有什么方法可以分隔行尾字符,但在 cmd 中仍然有效?我是否在 timeit 中对两个参数使用了错误的语法?

【问题讨论】:

  • 那不是将命令发送到 shell 需要多长时间,而不是命令运行需要多长时间?
  • 我认为它必须等待标准输出从第一个命令到达,然后才能发送退出,但这只是我的逻辑而不是技术理解
  • 实际上没有任何方法可以知道预期的输出量。
  • 我猜EOL是由\n提出的,所以你应该在p.stdin.write("dir\n")等中转义\ ,如下所示:p.stdin.write("dir\\n")

标签: python windows cmd timeit


【解决方案1】:

要解决 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 在这里不是合适的工具。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2019-02-18
    相关资源
    最近更新 更多