1

I'm using the subprocess module to start a subprocess (java program) and connect to it's output stream (stdout). But when i try to get its stdout there is no output.

p= subprocess.Popen(["java -Xmx256m -jar bin/HelloWorld.jar"],cwd=r'/home/karen/sphinx4-1.0beta5-src/sphinx4-1.0beta5/', shell=True, stdout=subprocess.PIPE, bufsize= 4024)

        out, err = p.communicate()
        print out

I want to be able to execute non-blocking reads on its stdout too. How can i do both things?

rypel
  • 4,686
  • 2
  • 25
  • 36
karensantana
  • 1,599
  • 4
  • 21
  • 34

2 Answers2

2

You need to split up the first arg into a list of your args; I think the reason you're getting no output is that your shell is looking to execute a file named "java -Xmx256m -jar bin/HelloWorld.jar" which clearly isn't going to exist. You want ["java", "-Xmx256m", "-jar", "bin/HelloWorld.jar"] as the first arg instead, like:

cmd = ["java", "-Xmx256m", "-jar", "bin/HelloWorld.jar"]
cwd = r'/home/karen/sphinx4-1.0beta5-src/sphinx4-1.0beta5/'
p = subprocess.Popen(cmd, cwd=cwd, shell=True, stdout=subprocess.PIPE, bufsize=4024 )

out, err = p.communicate()
print out

Re: wanting to execute non-blocking reads on stdout, see this other answer.

Community
  • 1
  • 1
pjz
  • 41,842
  • 6
  • 48
  • 60
  • `"java -Xmx256m -jar bin/HelloWorld.jar"` is the command that i want my shell runs... when i execute it on my shell it runs sucessfully! – karensantana Nov 29 '12 at 19:51
  • 1
    I understand - but that's a full command string, not a *filename* which is what your command is trying to execute. – pjz Nov 29 '12 at 19:52
0

This worked for me, with a HelloWorld that just does System.out.println("Hello World!");

import subprocess

p= subprocess.Popen(["java","-jar","HelloWorld.jar"], shell=True, stdout=subprocess.PIPE, bufsize= 4024)

out, err = p.communicate()
print out

This answer already covers reading non-blocking from a subprocess: python: nonblocking subprocess, check stdout

Community
  • 1
  • 1
John Fink
  • 313
  • 1
  • 4