C#或Python管道阻塞
我想把我用C#写的程序的标准输出直接传给另一个程序(比如Python脚本)。我的代码是用Console.Write()来输出内容,这在没有传输的时候工作得很好。监听命令只是用Console.Write()从一个设置好的套接字接收数据时写入数据到一个单独的线程。
[有效 - 数据在接收时写入控制台]
myProgram.exe listen
[无效 - 控制台没有任何输出]
myProgram.exe listen | python filter.py
我不太确定哪里出了问题,也没想出什么办法来排查这个问题。我猜问题可能是接收线程以某种方式阻止了标准输出将数据传递给另一个进程,但我不知道怎么测试这个。我希望能找到有想法的人,看看问题可能是什么,或者有什么方法可以进一步排查。如果需要代码来帮助理解,我可以提供一些代码片段。
我怎么判断问题出在C#还是Python上呢?
编辑:注意重定向操作符(>)是有效的。所以,myProgram.exe listen > log.txt确实会把写入标准输出的数据写入到log.txt文件中。我也尝试过参考这个例子:http://linux.byexamples.com/archives/343/python-handle-string-from-pipelines-and-list-of-param/。
[filter.py]
import sys
for line in sys.stdin:
sys.stdout.write(line)
编辑:控制台反馈
我觉得这值得提一下。Python脚本确实被调用了,但在等待了30秒后(它应该马上开始输出到标准输出),我按下Ctrl + C来停止这个进程,得到了以下结果。
>> myProgram.exe listen | python filter.py Traceback (most recent call last): File "filter.py", line 2, in for line in sys.stdin: KeyboardInterrupt ^C
编辑:@Aaronaught
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace echo
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (string arg in args)
{
Console.Out.WriteLine(arg);
}
}
else
{
Thread thread = new Thread(new ThreadStart(Receive));
thread.Start();
thread.Join();
}
}
static void Receive()
{
for (int i = 0; i < 10; i++)
{
Console.Out.WriteLine(i);
}
}
}
}
3 个回答
0
你可以去这里看看,搜索一下“死锁”。
也许这会对你有帮助。
0
你的Python程序需要两个EOF字符来结束。试试这个。
import sys
line=sys.stdin.readline()
while len(line):
sys.stdout.write(line)
line=sys.stdin.readline()
0
你的程序有没有在标准输出上写入换行符,或者调用了刷新操作?可能是因为它在缓存中,所以你看不到任何输出。