1

I have an executable jar which prints some information to the screen. I want to capture a specific number from the output which is the cost. There is a line "Cost = 10" for example and I want to have a list of costs when I run the jar file N times. I wanted to automate this process with a python script but since I am new to Python I do not know the best way to extract some data from stdout in a Python script. What would be the best way to do such task?

def wrapper(*args):
    process = Popen(list(args), stdout=subprocess.PIPE)
    process.communicate()
    return process

linkFileList = [ join(linkDir,f) for f in listdir(linkDir) if isfile(join(linkDir,f)) ]
nodeFileList = [ join(nodeDir,f) for f in listdir(nodeDir) if isfile(join(nodeDir,f)) ]
pairFileList = [ join(pairDir,f) for f in listdir(pairDir) if isfile(join(pairDir,f)) ]
size = len(linkFileList)
for count in range(0, size):
    x = wrapper('java', '-jar', 'C:\\Users\\fatma\\Documents\\workspace\\HeuristicRunnable.jar', nodeFileList[count], linkFileList[count], pairFileList[count])
fatma.ekici
  • 2,787
  • 4
  • 28
  • 30
  • There are several questions on stack overflow that this could be considered a duplicate of, check these: [get output](http://stackoverflow.com/questions/7604621/call-external-program-from-python-and-get-its-output) or [reading output](http://stackoverflow.com/questions/3804727/python-subprocess-reading-output-from-subprocess) – ken.ganong Jan 16 '13 at 19:47

1 Answers1

2

You're close. You want to do this instead:

def wrapper(*args):
    process = Popen(list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return stdout, stderr

The variables stdout and stderr will be simple strings corresponding to the output from stdout and stderr from the jar. I don't really think you can do anything with the process variable once you've used it, so there really isn't much point in returning it.

(I also included the code you need to get the stderr in case that also proves to be useful)

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224