如何在batch腳本中嵌入python代碼

老闆叫我幫他測一個命令在windows下消耗的時間,由於沒有裝windows那個啥工具包,沒有timeit那個命令,因而想本身寫一個,原理很簡單:python

REM timeit.bat

echo %TIME%
call %*
echo %TIME%

而後兩個時間減一下就能夠了,可是老是本身去減始終不方便,最好能直接算好打印出來。git

由於涉及到時間格式的解析,時間的運算,在batch下比較困難,天然就想到了python或者perl腳本,這裏首先想到的是python的-c參數:github

REM timeit.bat

set t1 = %TIME%
call %*
set t2 = %TIME%
python -c "some python code to compute the time elapsed"

可是,因爲計算的代碼會比較複雜,直接放在一行上很是難寫,也很是難讀,最好能分多行寫python代碼,咱們知道bash中有個heredoc,結合python的 「-」 參數:windows

# test.sh

echo this is a bash script
python - <<EOF
import math
print "this is python code"
print math.pi
EOF

無奈,batch並不支持heredoc,因此在要在batch中實現這個,用到一個很是magic的方法:原理就是個人腳本既是合法的batch,也是合法的python,而後在batch運行的最後用python調用自身:bash

1># : ^
'''
set t1 = %TIME%
call %*
set t2 = %TIME%
python %~f0"
exit /b
rem ^
'''
import os
import datetime
# python code to compute the time elapsed
print "Time Elapsed: xxx"

具體解釋能夠看這個問題:http://stackoverflow.com/questions/17467441/how-to-embed-python-code-in-batch-script工具

注意第一行奇怪的語法只是爲了把第二行合法的移到第一行,從而避免三個單引號這個非法命令調用出如今batch中。this

完整的timeit的實如今這裏:https://github.com/lzprgmr/privaterepo/blob/master/tools/Batch/timeit.batspa

 

最後,固然有人會說爲何不直接寫一個py而後在batch中調用 - 這固然能夠,但我想盡可能保持一個功能在一個腳本中,這樣看起來整潔,給別人用拷來拷去也不容易出錯。code