我正在我的计算机上用 C# 编写一个程序,该程序应该在远程 Raspberry Pi 上启动 Python 程序。目前,Python 代码只是每秒打印 'Hello'
。该程序应该永久运行。当我从 C# 启动此程序时,如果我的程序正在运行,我希望获得视觉反馈 - 我希望看到像 PuTTY 中一样的打印输出。
以下代码适用于像 ls
这样的命令。但由于我的 Python 程序 test.py
无法完成 - 我从未得到输出 - 我陷入了连续循环。
如何实时显示输出?
这是我的代码:
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
不使用终端仿真。
在没有终端仿真的情况下执行时,Python 会缓冲输出。所以你最终会得到输出,但只有在缓冲区填满之后。
要防止缓冲,请添加 -u
switch到python
命令行:
var command = ssh.CreateCommand("python3 -u test.py");
关于c# - 如何在本地控制台上使用 C# SSH.NET 执行的远程主机 (Raspberry Pi) 上运行的 Python 程序连续写入输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609499/