[英]How to execute multiple commands interactively in linux terminal from Java?
I want to run multiple commands in the linux terminal
and that will be one like as follows: 我想在linux terminal
运行多个命令,该命令将如下所示:
1. I will run suppose torch
and i wrote th
command and it opened the torch promt. 1.我会跑假设torch
和我写了th
命令,并将其打开火炬PROMT。
2. Now if i execute next command from java then it will run in the torch promt of the linux terminal. 2.现在,如果我从Java执行下一条命令,那么它将在linux终端的割炬程序中运行。
you can take another example like: 您可以举另一个例子:
1. At fist i will run python
in the linux terminal from java. 1.首先,我将从Java在linux终端中运行python
。
2. Then run 1+1
or anything in the python interpreter from java. 2.然后从Java运行python解释器中的1+1
或任何东西。
So here my second command is dependent on the first command. 所以在这里,我的第二条命令取决于第一条命令。 I want to run the commands in the terminal in a sequential way. 我想按顺序在终端中运行命令。
Edit : Another approach will do.Suppose i have a python interpreter running in linux terminal and now i want to execute a command from java that will run in the python interpreter of that particular opened linux terminal. 编辑 :另一种方法会做。假设我有一个在linux终端中运行的python解释器,现在我想从java中执行一个命令,该命令将在特定打开的linux终端的python解释器中运行。 Can i do that?? 我可以这样做吗?
I have tried to to run a command using this: 我试图使用以下命令运行命令:
String line;
try
{
String execstr= "th"; //It opens the torch promt in linux terminal.
Process p = Runtime.getRuntime().exec(execstr);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
/*if((line= input.readLine())==null)
System.out.println("blank");*/
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
But now after this command how can i run a command from java in the promt that means i want it interactively ?? 但是现在在执行此命令之后,如何在promt中从java运行命令,这意味着我希望以交互方式进行操作?
So how can i save the state of the previous command and use it for the next command?? 那么,如何保存上一个命令的状态并将其用于下一个命令?
Use p.getOutputStream()
to get a stream into which you can write the desired input for the program you run. 使用p.getOutputStream()
获取一个流,您可以在其中为运行的程序编写所需的输入。 (I know, the naming is a bit confusing). (我知道,命名有点混乱)。
Just the relevant part: 只是相关的部分:
Process p = Runtime.getRuntime().exec(execstr);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
OutputStream ops = p.getOutputStream();
ops.write("echo hello world".getBytes());
ops.close();
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
input.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.