【发布时间】: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")