如何从本地控制台上用C#SSH.NET执行的远程主机(Raspberry Pi)上运行的Python程序连续写入输出? [英] How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console?

查看:187
本文介绍了如何从本地控制台上用C#SSH.NET执行的远程主机(Raspberry Pi)上运行的Python程序连续写入输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计算机上用C#编写一个程序,该程序应在远程Raspberry Pi上启动Python程序.目前,Python代码仅每秒打印一次'Hello'.该程序应永久运行.当我从C#启动此程序时,如果我的程序正在运行,我希望获得视觉反馈–我希望看到打印的输出,就像在PuTTY中一样.

I'm writing a program in C# on my computer which should start a Python program on a remote Raspberry Pi. For the moment the Python code is just printing 'Hello' every second. The program should run permanently. When I start this program from C#, I would like to have a visual feedback, if my program is running – I'd like to see the printed output like in PuTTY.

以下代码对于ls之类的命令运行正常.但是由于我的Python程序test.py不能完成的原因-我从没得到输出-我陷入了连续循环.

The following code works fine for a command like ls. But for the reason that my Python program test.py should not finish – I never get an output – I's stuck in a continuous loop.

如何实时显示输出?

这是我的代码:

using Renci.SshNet;

static void Main(string[] args)
{
    var ssh = new SshClient("rpi", 22, "pi", "password");
    ssh.Connect();

    var command = ssh.CreateCommand("python3 test.py");
    var asyncExecute = command.BeginExecute();

    while (true)
    {
        command.OutputStream.CopyTo(Console.OpenStandardOutput());
    }
}

推荐答案

SSH.NET SshClient.CreateCommand不使用终端仿真.

SSH.NET SshClient.CreateCommand does not use a terminal emulation.

在没有终端仿真的情况下执行时,Python缓冲输出.这样,您最终将获得输出,但仅在缓冲区填满之后才能获得输出.

Python buffers the output, when executed without terminal emulation. So you would get the output eventually, but only after the buffer fills.

为防止缓冲,请添加 -u开关python命令行:

To prevent the buffering, add -u switch to python commandline:

var command = ssh.CreateCommand("python3 -u test.py");

这篇关于如何从本地控制台上用C#SSH.NET执行的远程主机(Raspberry Pi)上运行的Python程序连续写入输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆