0

I am calling java.lang.Runtime.exec(...) but this seems to accept the command lines as an array and I want to use a single string.

How can I do the same using a single string?

Peter Bagyinszki
  • 1,069
  • 1
  • 10
  • 29
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 2
    There is a `Runtime.exec(String command)` method, see your link. And everyone who uses `Runtime.exec(...)` should read this: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html – Peter Bagyinszki Jun 01 '12 at 16:55
  • @PeterBagyinszki Thank! Now the only problem is that I do want to setup the current directory and still run it as a single command. – sorin Jun 01 '12 at 16:58
  • There is a method for that too: `exec(String command, String[] envp, File dir)` – Peter Bagyinszki Jun 01 '12 at 17:13
  • This is exactly what I am doing not and Java is complaining that it cannot find `python`. The command line executed is something like `python file ....` and envp is `null`, and obviously python is installed (linux) and also in `PATH`. – sorin Jun 01 '12 at 17:46

4 Answers4

2

From the linked Javadocs:

envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

So just pass in null for the second parameter, and the environment will be inhereted.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
2

If you pass null for the second paramter the current environment will be inherited.

If you want to modify the current environment, you can build it from System.getEnv() like this:

private static String[] getEnv() {
    Map<String, String> env = System.getenv();
    String[] envp = new String[env.size()];
    int i = 0;
    for (Map.Entry<String, String> e : env.entrySet()) {
        envp[i++] = e.getKey() + "=" + e.getValue();
    }
    return envp;
}

Update

You can check your Java path with System.out.println(System.getenv("PATH"));

If path is ok, then try it with

String[] commands = new String[] { "bash", "-c", "python foo/bar.py" };
Runtime.getRuntime().exec(commands, null, new File("/workingDir"));
Peter Bagyinszki
  • 1,069
  • 1
  • 10
  • 29
1

From the documentation:

envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

It sounds like you want to pass null for that argument.

Gabe
  • 84,912
  • 12
  • 139
  • 238
0

Currently there is no way of calling a system command with a command line as a single string and be able to specify the current directory.

It seems that Java API is missing this basic feature :)

The workaround is to use the array version instead of string.

sorin
  • 161,544
  • 178
  • 535
  • 806