Java 使用不同的解释器执行shell脚本
我试图使用一个执行python脚本,我想要的是使用另一个解释器(shebang)从.sh文件运行python脚本 以下是我的shell脚本文件(fileExec.sh)的内容: 自从我得到以下信息后,shebang似乎无法更改: bash:print命令找不到 以下是我的Java代码:Java 使用不同的解释器执行shell脚本,java,python,jsch,Java,Python,Jsch,我试图使用一个执行python脚本,我想要的是使用另一个解释器(shebang)从.sh文件运行python脚本 以下是我的shell脚本文件(fileExec.sh)的内容: 自从我得到以下信息后,shebang似乎无法更改: bash:print命令找不到 以下是我的Java代码: session = newSessionFor(user, host, port); Channel channel = session.openChannel("exec"); File shFile = n
session = newSessionFor(user, host, port);
Channel channel = session.openChannel("exec");
File shFile = new File("fileExec.py");
FileWriter writer = new FileWriter(shFile);
writer.write(shebang + "\n");
writer.write(command);
writer.close();
PrintWriter printWriter = new PrintWriter(shFile);
printWriter.println(shebang);
printWriter.println(command);
printWriter.close();
((ChannelExec) channel).setCommand(FileUtils.readFileToByteArray(shFile));
我对Java不是很在行,但可能是在检查hashbang之前先检查文件扩展名。您应该将文件更改为
fileExec.py
以确保,或者只更改为fileExec
(您似乎在java代码中调用了错误的文件?文件扩展名不应该相关,但为了保持一致性,您通常不会调用python脚本
fileExec.sh
如果您从命令行测试fileExec.sh
,假设您对其设置了执行权限,那么它应该可以工作:
$ chmod +x fileExec.sh
$ ./fileExec.sh
hello from python
但是,无需依赖shebang和更改文件权限,只需执行以下操作:
$ python fileExec.sh
从命令行和java程序
((ChannelExec)channel).setCommand("/usr/bin/python /path/to/fileExec.sh");
shebang仅由操作系统在执行文件时使用 您不是在执行文件,而是将python文件的内容复制粘贴到shell提示符上 如果不想在服务器上存储和执行文件,可以使用
Python-cyourcommand
从shell运行Python命令。以下是终端的外观,请随意尝试:
user@host ~$ python -c 'print "hello world"'
hello world
要在程序中执行此操作,请添加一个方法以转义shell中的任意字符串:
static String escapeForShell(String s) {
return "'" + s.replaceAll("'", "'\\\\''") + "'";
}
然后跑
((ChannelExec) channel).setCommand("python -c " + escapeForShell(command));
其中String命令=“打印‘来自python的hello’”代码>
((ChannelExec) channel).setCommand("python -c " + escapeForShell(command));