Python 问题:
$ python -V
Python 2.4.3
搜索了这个问题的答案,可能不知道使用什么搜索。
基本上这个问题很简单。 我有这样的 perl 代码,它运行完美。
while ($count)
{
$count = sysread(STDIN,$data,2000);
if ($count)
{
#print "Read $data\n";
showHex($data);
$s->mcast_send($data,"$MulticastIP:$MulticastPort");
}
}
这正是我想要的,即使 sysread 的最大读取数为 2000,如果它已读取至少一个字节并且在传入的数据中存在延迟,也会提前返回数据。
重要提示:我的传入数据是原始二进制数据,而不是换行符分隔的文本。
我在 python 中需要这个,因为默认情况下,perl 中的 IO::Socket::Multicast 在 perl 库中不是标准的。
但我不知道如何在 python 中执行此操作。 Python 烦人地等到所有 2000 个字节都被读取后再返回。
我的 python 代码:go.py(对于这个例子,我一次只读取 10 个字节)
#!/bin/env python
import sys
while True:
buf = sys.stdin.read(10)
if len(buf) > 0:
print "Read %d" % (len(buf))
问题证明:go.sh
while (( 1 ))
do
echo Sending ab 1>&2
echo ab
sleep 1
done | ./go.py
Sending ab
Sending ab
Sending ab
Sending ab
Read 10
Sending ab
Sending ab
Sending ab
Read 10
我从经验中知道,如果任何文件描述符上的 read() 已经读取了至少一个字节并且到达没有更多数据可立即读取的点,就像从 stdout 输出的管道另一个程序。
READ(2) Linux Programmer’s Manual READ(2)
NAME
read - read from a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
DESCRIPTION
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecified.
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes
requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or
because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
那么我该如何实现呢?
请您参考如下方法:
我想我找到了最好的方法。除非有人能弄清楚如何使 read 的行为像 perl 中的 C 和 sysread。 我像上面那样让它成为非阻塞的,但是使用 select 等待数据可用。结合两者,我得到了我想要的。等待数据可用,不阻塞地读取可用数据。是啊!!!!!!
import os
import sys
import select
import fcntl
# Make stdin non blocking
flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK)
while True:
rlist,a,a = select.select( [sys.stdin.fileno()], [], [] )
for f in rlist:
try:
buf = sys.stdin.read(1000)
except IOError:
print "IOError"
buf = []
if len(buf) > 0:
print "Read %d" % (len(buf))
else:
print "No Data Available"
输出:注意..我从未看到“IOError”或“无可用数据”
Sending ab
Read 3
Sending ab
Read 3
Sending ab
Read 3
Sending ab
Read 3
