How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console?

自作多情 提交于 2019-12-23 02:50:05

问题


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.

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.

How can I display the output in real-time?

Here's my code:

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());
    }
}

回答1:


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

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

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

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



回答2:


If you want the output from your remote program on your local host the remote program ("test.py") will have to talk to your local host. The local host running your c#-program can then print something whenever it gets a message from the RPi. Commonly, after initiation of your test.py on RPi, you can send a single message back to your local host, such as "Started" or "0", or whatever you'd like.

If you have an active SSH window running the test.py, you can print directly to it from the RPi.



来源:https://stackoverflow.com/questions/57609499/how-to-continuously-write-output-from-python-program-running-on-a-remote-host-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!