简体   繁体   中英

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

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

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM