Java ProcessBuilder:环境设置正确,但仍未找到命令 [英] Java ProcessBuilder: environment set correctly but still command not found

查看:309
本文介绍了Java ProcessBuilder:环境设置正确,但仍未找到命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在正在开发的Eclipse插件上使用Java的ProcessBuilder遇到麻烦. 我可以在调用start()方法之前正确设置环境,但是当我运行该程序时,它总是返回命令未找到错误.

I am having troubles with Java's ProcessBuilder on an Eclipse plugin I'm developing. I correctly set the environment before calling the start() method, but when I run the program, it always returns a command not found error.

当我通过命令行调用命令时,它运行良好.

When I call the command via command line it works perfectly.

当我根据需要在环境中启动Eclipse时,找到了命令,程序运行正常.

When I start the eclipse with the environment as I require, the command is found and the program works fine.

仅当我以编程方式设置环境时,程序才会失败.

Only when I set the environment programatically, the program fails.

这就是我所拥有的:

ProcessBuilder pb = new ProcessBuilder("my_command", file, output);
Map<String, String> env = pb.environment();
env.put("PATH", env.get("PATH") + File.pathSeparator + env1 + File.pathSeparator + env2);
Process p = pb.start();
...

其中,env1env2是我要添加到PATH变量的路径...

where, env1 and env2 are the paths I want to add to the PATH variable...

此代码有什么问题?

提前谢谢!

推荐答案

我认为,您在ProcessBuilder上设置的环境仅是传递给新流程的内容,而不是构建器本身使用的环境.在尝试开始之前,请尝试设置Java进程的环境变量新过程.

I think, the environment you set on the ProcessBuilder is only what is passed to the new process but not what is used by the builder itself. Try setting the environment variables of your Java process before trying to start the new process.

看到可能无法更改Java进程的环境,我相信您必须提出一些解决方法.

Seeing that it may not be possible to alter the Java process's environment, I believe you have to come up with some work-around.

当您已经知道要寻找的路径时,您当然可以自己找出通向"my_command"的完整路径,大约是这样:

When you already know the path(s) you are looking for you can of course figure out the full path to "my_command" yourself, about so:

String commandString;

if ( new File(env1 + "/my_command").isFile() ) {
  commandString = env1 + "/my_command";
} else
if ( new File(env2 + "/my_command").isFile() ) {
  commandString = env2 + "/my_command";
}

ProcessBuilder pb = new ProcessBuilder(commandString, file, output);

如果"my_command"可能已经在用户的PATH元素之一中,则

可能不切实际.

Might be impractical though, if "my_command" may already be in one of the user's PATH elements.

这篇关于Java ProcessBuilder:环境设置正确,但仍未找到命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆