我有一個.bat腳本正在計算一個進程的執行時間。具體如下:如何從.bat腳本獲取返回值?
set startTime=%time%
YourApp.exe
echo Start Time: %startTime%
echo Finish Time: %time%
現在,我想「結束時間」返回從這個蝙蝠腳本調用的腳本的一些變量,但我沒有得到我應如何從蝙蝠腳本返回值。請建議我該如何實現它。
我有一個.bat腳本正在計算一個進程的執行時間。具體如下:如何從.bat腳本獲取返回值?
set startTime=%time%
YourApp.exe
echo Start Time: %startTime%
echo Finish Time: %time%
現在,我想「結束時間」返回從這個蝙蝠腳本調用的腳本的一些變量,但我沒有得到我應如何從蝙蝠腳本返回值。請建議我該如何實現它。
您可以結合subprocess
和正則表達式來解析輸出
import subprocess
import re
output = subprocess.Popen(
("yourBatch.bat", "arguments1", "argument2"),
stdout=subprocess.PIPE).stdout
finish_time_search = re.search('Finish Time: (.*)', output[1], re.IGNORECASE)
if finish_time_search:
finish_time = finish_time_search.group(1)
output.close()
我照你所說的做了,但是在執行我的python腳本時出現錯誤,如「文件」C:\ programs \ Python27 \ lib \ re.py「,第146行,在搜索返回_compile(模式,標誌)。搜索(字符串) TypeError:預期的字符串或緩衝區現在有什麼錯? – Learner
因爲輸出是一個列表(你的批輸出的行),並且你正在尋找的行是seconde。我編輯了我的代碼 –
從腳本方面:
這是很容易解析叫蝙蝠輸出,讓你需要在不退出信息碼。您可以使用子進程命令和通信方法來分析輸出。據報道在Python幫助:
https://docs.python.org/2/library/subprocess.html
output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
從DOS側:
您可以使用 「退出」 命令:
exit /b %errorlevel%
並使用ERRORLEVEL爲你的purpouse。 請更多信息,請看:
http://www.computerhope.com/exithlp.htm
另一種選擇是使用和命令「SETX」(使用寄存器,它是不揮發),或一個文件作爲環境變量臨時存儲。
你是什麼意思?您是否希望將完成時間存儲在環境變量(如「開始時間」)中,還是希望腳本在控制檯上輸出「完成時間」以在調用腳本中捕獲它? – aschipfl
您可能對[此主題](http://stackoverflow.com/q/673523/5047996)有關測量執行時間... – aschipfl
@aschipfl我想要回到計算和返回的過程的完成時間從.bat到Python腳本的值 – Learner