简体   繁体   English

如何在Ubuntu中从Java执行Perl脚本

[英]How to execute perl script from java in ubuntu

I have a perl script that needs 2 arguments to be run. 我有一个需要2个参数才能运行的perl脚本。 I am currently using Ubuntu and I managed to execute the perl script from terminal by changing directory to where the perl script exists and by writing 我目前正在使用Ubuntu,并且通过将目录更改为perl脚本所在的位置并通过编写来设法从终端执行perl脚本

perl tool.pl config=../mydefault.config file=../Test

However, when I am trying to run the perl script from my java program (I am using eclipse), It always gives me the message Command Failure . 但是,当我尝试从Java程序运行perl脚本时(我正在使用eclipse),它总是给我消息Command Failure This is the code : 这是代码:

Process process;
try {
    process = Runtime.getRuntime().exec("perl /home/Leen/Desktop/Tools/bin/tool.pl config=../mydefault.config file=../Test");
    process.waitFor();
    if(process.exitValue() == 0) {
        System.out.println("Command Successful");
    } else {
        System.out.println("Command Failure");
    }
} catch(Exception e) {
    System.out.println("Exception: "+ e.toString());
}

So please what is wrong in my code? 所以,请问我的代码有什么问题?

You should be separating the command from it's arguments in the call to exec() , such as: 您应该在对exec()的调用中将命令与其参数分开 ,例如:

Runtime.getRuntime().exec(new String[] {"perl", "/home/Leen...", "config=...", "file=..."});

With what you currently have, Runtime is looked for a command literally named perl /home/Leen/Desktop... , spaces and all. 使用当前拥有的内容,Runtime会查找一个字面名为 perl /home/Leen/Desktop... ,空格和全部的命令。

When you run the whole command from the Terminal, your shell is smart enough to realize that a space delimits the name of the command ( perl ) from the arguments that should be passed to it ( /home/Leen/Desktop... , config=... , file=... ). 当您从终端中运行整个命令,你的shell是足够聪明,意识到一个空间界定命令的名称( perl从应传递给它的参数)( /home/Leen/Desktop...config=...file=... )。 Runtime.exec() is not that smart. Runtime.exec()并不那么聪明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM