jsch运行一个远程python文件,python完成后才能得到输出

2024-09-27 00:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用jsch“exec”运行python文件。我只在python完成后才得到输出。很奇怪。它应该在进程运行时输出。 java代码是

package com.demo.jsch;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.*;

public class App3 {
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    String user = "root";
    String host = "10.17.1.183";
    int port = 22;
    String password = "whoami!";
    String cmd = "source /etc/profile; /home/script/test.py";

    Session session = jSch.getSession(user, host, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(30000);
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(cmd);

    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), "utf8"));
    OutputStream out = channel.getOutputStream();

    channel.connect();

    String line = null;
    while (true) {
        line = in.readLine();
        if(line != null){
            System.out.println(line);
        }else{
            if(channel.isClosed()){
                System.out.println("退出状态" + channel.getExitStatus());
                break;
            }else{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    channel.disconnect();
    session.disconnect();
}
}

python文件测试.py是

^{pr2}$

在测试.py但是我的输出应该是每秒一次jsch.java公司在10秒前没有输出,它一次获得所有输出。在


Tags: pyimportcomnewstringsessionlinechannel

热门问题