3

I have a small java program that I can run from the command line using this syntax:

java -jar EXEV.jar -s:myfile

This java program print some data to the screen and I want redirect stdout into a file called output.txt.

from subprocess import Popen, PIPE

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

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile', '>', 'output.txt')

When I run the above, output.txt is never written to and Python does not throw any errors. Can anyone help me figure out the problem?

1 Answer 1

3

You need to either use stdout=output where output is an open file for writing to 'output.txt' and remove the output redirection from the command, or leave the output redirection in the command and use shell=True with no stdout argument:

Option 1:

from subprocess import Popen

def wrapper(*args):
    output = open('output.txt', w)
    process = Popen(list(args), stdout=output)
    process.communicate()
    output.close()
    return process

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile')

Option 2:

from subprocess import Popen

def wrapper(*args):
    process = Popen(' '.join(args), shell=True)
    process.communicate()
    return process

x = wrapper('java', '-jar', 'EXEV.jar', '-s:myfile', '>', 'output.txt')
Sign up to request clarification or add additional context in comments.

1 Comment

And of these, the first is better: there's no reason to use the shell's redirection when Python provides the facilities already.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.