我正在使用运行时从我的Java程序运行命令提示符命令.但是我不知道如何获得命令返回的输出.
这是我的代码:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send" , argument};
Process proc = rt.exec(commands);
Run Code Online (Sandbox Code Playgroud)
我尝试过,System.out.println(proc);但没有返回任何东西.该命令的执行应返回由分号分隔的两个数字,我怎样才能在变量中打印出来?
这是我现在使用的代码:
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
InputStream stdIn = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdIn);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
Run Code Online (Sandbox Code Playgroud)
但我没有得到任何东西作为我的输出,但当我自己运行该命令它工作正常.
我可以执行类似的Linux命令ls或pwd没有问题从Java,但不能得到执行的Python脚本.
这是我的代码:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Run Code Online (Sandbox Code Playgroud)
没啥事儿.它达到SEND但它刚刚停止......
我正在尝试执行需要root权限的脚本,因为它使用串行端口.另外,我必须传递带有一些参数(包)的字符串.
我正在使用Python 3.4。
我有一个Python脚本myscript.py:
import sys
def returnvalue(str) :
if str == "hi" :
return "yes"
else :
return "no"
print("calling python function with parameters:")
print(sys.argv[1])
str = sys.argv[1]
res = returnvalue(str)
target = open("file.txt", 'w')
target.write(res)
target.close()
Run Code Online (Sandbox Code Playgroud)
我需要从 java 类调用这个 python 脚本PythonJava.java
public class PythonJava
{
String arg1;
public void setArg1(String arg1) {
this.arg1 = arg1;
}
public void runPython()
{ //need to call myscript.py and also pass arg1 as its arguments.
//and also myscript.py …Run Code Online (Sandbox Code Playgroud)