Using os.execvp in Python

I have a question about using os.execvp in Python. I have the following bit of code that was used to create a list of arguments:

  args = ["java"
        classpath
        , "-Djava.library.path =" + lib_path ()
        , ea
        , "-Xmx1000m"
        , "-server"
        , "code_swarm"
        , params
        ]

When I output the line using " ".join(args) and paste it into the prompt of my shell, the JVM starts up fine and everything works. Everything works if I use os.system(" ".join(args)) in my Python script too.

But the following bit of code does not work:

  os.execvp ("java", args) 

I get the following error:

  Unrecognized option: -classpath [and then the classpath I created, which looks okay]
 Could not create the Java virtual machine.

So what gives? Why does copying / pasting into the shell or using os.system() work, but not os.execvp() ?

+6
python shell exec
source share
2 answers

If your classpath variable contains, for example, -classpath foo.jar, it will not work, since it thinks the parameter name is -classpath foo.jar. Divide it into two arguments: [..., "-classpath", classpath, ...].

Other methods (copy and paste and system ()) work because the shell breaks the command line in spaces (unless they are escaped or quoted). The command line is actually passed to the called program as an array (unlike Windows), and the JVM expects to find an element with only "-classpath", followed by another element with classpath.

You can see the difference for yourself by calling the following small Python script instead of the JVM:

 #!/usr/bin/python import sys print sys.argv 
+11
source share

Make sure you do not rely on shell extensions in your class path. For example. "~ / my.jar" will be expanded by the shell in the os.system call, but no, I believe in the os.execvp call.

0
source share

All Articles