2016-03-22 38 views
0

我有一个.bat脚本正在计算一个进程的执行时间。具体如下:如何从.bat脚本获取返回值?

set startTime=%time% 
YourApp.exe 
echo Start Time: %startTime% 
echo Finish Time: %time% 

现在,我想“结束时间”返回从这个蝙蝠脚本调用的脚本的一些变量,但我没有得到我应如何从蝙蝠脚本返回值。请建议我该如何实现它。

+0

你是什么意思?您是否希望将完成时间存储在环境变量(如“开始时间”)中,还是希望脚本在控制台上输出“完成时间”以在调用脚本中捕获它? – aschipfl

+0

您可能对[此主题](http://stackoverflow.com/q/673523/5047996)有关测量执行时间... – aschipfl

+0

@aschipfl我想要回到计算和返回的过程的完成时间从.bat到Python脚本的值 – Learner

回答

1

您可以结合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() 
+0

我照你所说的做了,但是在执行我的python脚本时出现错误,如“文件”C:\ programs \ Python27 \ lib \ re.py“,第146行,在搜索返回_compile(模式,标志)。搜索(字符串) TypeError:预期的字符串或缓冲区现在有什么错? – Learner

+0

因为输出是一个列表(你的批输出的行),并且你正在寻找的行是seconde。我编辑了我的代码 –

0

从脚本方面:

这是很容易解析叫蝙蝠输出,让你需要在不退出信息码。您可以使用子进程命令和通信方法来分析输出。据报道在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”(使用寄存器,它是不挥发),或一个文件作为环境变量临时存储。