0

I have a .bat script which is calculating the execution time of a process. As follows:

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

Now, i want to return "Finish Time" to some variable of the script from which this .bat script is called but i am not getting how shall i return the value from the .bat script. Kindly suggest how shall i acheive it.

Learner
  • 413
  • 10
  • 25
  • What do you mean? Do you want Finish Time to be stored in an environment variable (like Start Time), or do you want the script to output the Finish Time on the console to capture it in the calling script? – aschipfl Mar 22 '16 at 09:11
  • You might be interested in [this thread](http://stackoverflow.com/q/673523/5047996) concerning measurement of execution time... – aschipfl Mar 22 '16 at 09:22
  • @aschipfl i want to get back the finish time of a process calculated and returning the value from .bat into a python script – Learner Mar 22 '16 at 09:52
  • I understand, but there are many ways (environment variables, console output at _STDOUT_, temporary files,...); you should clarify which channel you want to go for... – aschipfl Mar 22 '16 at 09:55

2 Answers2

1

You can combine subprocess and regex to parse the output

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()
Ghilas BELHADJ
  • 11,080
  • 9
  • 48
  • 82
  • i did as you said but i am getting error while executing my python script as "File "C:\programs\Python27\lib\re.py", line 146, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer. What is wrong now? – Learner Mar 22 '16 at 10:49
  • because output is a list ( lines of your batch output ), and the line you're looking for is the seconde. I've edited my code – Ghilas BELHADJ Mar 22 '16 at 11:07
0

From the script side:

It is easy to parse the called bat output and get the information you need without an exit code. You can use the subprocess command and the communicate method to parse the output. As reported in the python help:

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]

From the DOS side:

You can use the "exit" command:

exit /b %errorlevel%

And use errorlevel for your purpouse. Please, for more info, look at:

http://www.computerhope.com/exithlp.htm

Another option is to use and environment variable with the command "setx" (which uses a register and it is not volatile), or a file as a temp storage.

J_Zar
  • 1,334
  • 1
  • 15
  • 27