如何从在本地控制台上使用 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?
问题描述
我正在我的计算机上用 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屋!