I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: c:\test>java -jar run_this.jar required_parameter.ext
? I'm a python newbie so details are greatly appreciated. Thanks in advance.
views:
721answers:
2
+1
A:
In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd().
On Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java.
Martin v. Löwis
2008-11-18 16:27:24
Why os.system in preference to subprocess.Popen?
S.Lott
2008-11-18 16:50:04
I personally find the subprocess API too overloaded for a beginner (even though it allows to specify the cwd of the new process, making the restore unnecessary).
Martin v. Löwis
2008-11-18 23:52:45
+1
A:
Here is a small script to get you started. There are ways to make it "better", but not knowing the full scope of what you are trying to accomplish this should be sufficient.
import os
if __name__ == "__main__":
startingDir = os.getcwd() # save our current directory
testDir = "\\test" # note that \ is windows specific, and we have to escape it
os.chdir(testDir) # change to our test directory
os.system("java -jar run_this.jar required_paramter.ext")
os.chdir(startingDir) # change back to where we started
grieve
2008-11-18 16:59:37