David542
David542

Reputation: 110267

How to execute a file that requires being in the same directory?

I have a python script that needs to execute a .jar file that is located in another directory. What would be the best way to do this? So far I was thinking -

subprocess.call(["cd","/path/to/file"])
subprocess.call(["./file.jar"])

How should I do this?

Update:

Using both of the answers below, this is what I ended up doing:

subprocess.call(shlex.split("./file.jar -rest -of -command"), cwd=COMMAND_FOLDER)

Upvotes: 3

Views: 123

Answers (2)

unutbu
unutbu

Reputation: 879869

To run a process in a different current working directory, use subprocess.Popen's cwd parameter:

import subprocess
proc = subprocess.Popen(['file.jar'], cwd = '/path/to/file')

Upvotes: 7

Fredrik Pihl
Fredrik Pihl

Reputation: 45672

howabout using:

import subprocess
import shlex

cmd = "the command to use to execute your binary"


args = shlex.split(cmd)
try:
    p = subprocess.call(args)
except OSError, e:
    print >>sys.stderr, "Execution failed:", e

Upvotes: 2

Related Questions