- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何确定对 sys.stdin.readline() (或更一般地说,任何基于文件描述符的文件对象上的 readline() )的调用是否会阻塞?
当我在 python 中编写基于行的文本过滤程序时会出现这种情况;
也就是说,程序反复从输入中读取一行文本,可能对其进行转换,然后将其写入输出。
我想实现一个合理的输出缓冲策略。
我的标准是:
#!/usr/bin/python
# cat-n.linebuffered.py
import sys
num_lines_read = 0
while True:
line = sys.stdin.readline()
if line == '': break
num_lines_read += 1
print("%d: %s" % (num_lines_read, line))
sys.stdout.flush()
#!/usr/bin/python
# cat-n.defaultbuffered.py
import sys
num_lines_read = 0
while True:
line = sys.stdin.readline()
if line == '': break
num_lines_read += 1
print("%d: %s" % (num_lines_read, line))
#!/usr/bin/python
num_lines_read = 0
while True:
if sys_stdin_readline_is_about_to_block(): # <--- How do I implement this??
sys.stdout.flush()
line = sys.stdin.readline()
if line == '': break
num_lines_read += 1
print("%d: %s" % (num_lines_read, line))
sys_stdin_readline_is_about_to_block()
?
select([sys.stdin],[],[],0)
查看从 sys.stdin 读取是否会阻塞。 (当 sys.stdin 是缓冲文件对象时,这不起作用,至少有一个可能有两个原因:(1)如果部分行准备好从底层输入管道读取,它会错误地说“不会阻塞”, (2) 如果 sys.stdin 的缓冲区包含一个完整的输入行,但底层管道还没有准备好进行额外的读取,它会错误地说“将阻塞”......我认为)。 os.fdopen(sys.stdin.fileno(), 'r')
和 fcntl
和 O_NONBLOCK
(我无法让它在任何 python 版本中与 readline() 一起使用:readline()
循环并将每一行传递给主#!/usr/bin/python
# cat-n.threaded.py
import queue
import sys
import threading
def iter_with_abouttoblock_cb(callable, sentinel, abouttoblock_cb, qsize=100):
# child will send each item through q to parent.
q = queue.Queue(qsize)
def child_fun():
for item in iter(callable, sentinel):
q.put(item)
q.put(sentinel)
child = threading.Thread(target=child_fun)
# The child thread normally runs until it sees the sentinel,
# but we mark it daemon so that it won't prevent the parent
# from exiting prematurely if it wants.
child.daemon = True
child.start()
while True:
try:
item = q.get(block=False)
except queue.Empty:
# q is empty; call abouttoblock_cb before blocking
abouttoblock_cb()
item = q.get(block=True)
if item == sentinel:
break # do *not* yield sentinel
yield item
child.join()
num_lines_read = 0
for line in iter_with_abouttoblock_cb(sys.stdin.readline,
sentinel='',
abouttoblock_cb=sys.stdout.flush):
num_lines_read += 1
sys.stdout.write("%d: %s" % (num_lines_read, line))
| cat
是默认情况下制作 python 块缓冲区而不是行缓冲区。)
for which in defaultbuffered linebuffered threaded; do
for python in python2.7 python3.5; do
echo "$python cat-n.$which.py:"
(echo z; echo -n a; sleep 1; echo b; sleep 1; echo -n c; sleep 1; echo d; echo x; echo y; echo z; sleep 1; echo -n e; sleep 1; echo f) | $python cat-n.$which.py | cat
done
done
python2.7 cat-n.defaultbuffered.py:
[... pauses 5 seconds here. Bad! ...]
1: z
2: ab
3: cd
4: x
5: y
6: z
7: ef
python3.5 cat-n.defaultbuffered.py:
[same]
python2.7 cat-n.linebuffered.py:
1: z
[... pauses 1 second here, as expected ...]
2: ab
[... pauses 2 seconds here, as expected ...]
3: cd
4: x
5: y
6: z
[... pauses 2 seconds here, as expected ...]
6: ef
python3.5 cat-n.linebuffered.py:
[same]
python2.7 cat-n.threaded.py:
[same]
python3.5 cat-n.threaded.py:
[same]
for which in defaultbuffered linebuffered threaded; do
for python in python2.7 python3.5; do
echo -n "$python cat-n.$which.py: "
timings=$(time (yes 01234567890123456789012345678901234567890123456789012345678901234567890123456789 | head -1000000 | $python cat-n.$which.py >| /tmp/REMOVE_ME) 2>&1)
echo $timings
done
done
/bin/rm /tmp/REMOVE_ME
python2.7 cat-n.defaultbuffered.py: real 0m1.490s user 0m1.191s sys 0m0.386s
python3.5 cat-n.defaultbuffered.py: real 0m1.633s user 0m1.007s sys 0m0.311s
python2.7 cat-n.linebuffered.py: real 0m5.248s user 0m2.198s sys 0m2.704s
python3.5 cat-n.linebuffered.py: real 0m6.462s user 0m3.038s sys 0m3.224s
python2.7 cat-n.threaded.py: real 0m25.097s user 0m18.392s sys 0m16.483s
python3.5 cat-n.threaded.py: real 0m12.655s user 0m11.722s sys 0m1.540s
最佳答案
你当然可以用 select
: 这就是它的用途,它的性能对于少量的文件描述符来说是好的。您必须自己实现行缓冲/中断,以便您可以检测在缓冲(结果是)部分行后是否有更多可用输入。
你可以自己做所有的缓冲(这是合理的,因为 select
在文件描述符级别操作),或者你可以设置 stdin
非阻塞并使用 file.read()
或 BufferedReader.read()
(取决于您的 Python 版本)使用任何可用的东西。如果您的输入可能是 Internet 套接字,则无论缓冲如何,您都必须使用非阻塞输入,因为 select
的常见实现可以虚假地指示来自套接字的可读数据。 (在这种情况下,Python 2 版本使用 IOError
引发 EAGAIN
;Python 3 版本返回 None
。)
( os.fdopen
在这里没有帮助,因为它不会为 fcntl
使用创建新的文件描述符。在某些系统上,您可以使用 /dev/stdin
打开 O_NONBLOCK
。)
基于默认(缓冲)的 Python 2 实现 file.read()
:
import sys,os,select,fcntl,errno
fcntl.fcntl(sys.stdin.fileno(),fcntl.F_SETFL,os.O_NONBLOCK)
rfs=[sys.stdin.fileno()]
xfs=rfs+[sys.stdout.fileno()]
buf=""
lnum=0
timeout=None
rd=True
while rd:
rl,_,xl=select.select(rfs,(),xfs,timeout)
if xl: raise IOError # "exception" occurred (TCP OOB data?)
if rl:
try: rd=sys.stdin.read() # read whatever we have
except IOError as e: # spurious readiness?
if e.errno!=errno.EAGAIN: raise # die on other errors
else: buf+=rd
nl0=0 # previous newline
while True:
nl=buf.find('\n',nl0)
if nl<0:
buf=buf[nl0:] # hold partial line for "processing"
break
lnum+=1
print "%d: %s"%(lnum,buf[nl0:nl])
timeout=0
nl0=nl+1
else: # no input yet
sys.stdout.flush()
timeout=None
if buf: sys.stdout.write("%d: %s"%(lnum+1,buf)) # write any partial last line
cat -n
,我们可以在获得它们后立即写出部分行,但这会保留它们以表示一次处理整行。
yes
测试需要“真正的 0m2.454s 用户 0m2.144s 系统 0m0.504s”。
关于python - 你如何判断 sys.stdin.readline() 是否会阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893192/
尝试使用集成到 QTCreator 的表单编辑器,但即使我将插件放入 QtCreator.app/Contents/MacOS/designer 也不会显示。不过,相同的 dylib 文件确实适用于独
在此代码示例中。 “this.method2();”之后会读到什么?在返回returnedValue之前会跳转到method2()吗? public int method1(int returnedV
我的项目有通过gradle配置的依赖项。我想添加以下依赖项: compile group: 'org.restlet.jse', name: 'org.restlet.ext.apispark', v
我将把我们基于 Windows 的客户管理软件移植到基于 Web 的软件。我发现 polymer 可能是一种选择。 但是,对于我们的使用,我们找不到 polymer 组件具有表格 View 、下拉菜单
我的项目文件夹 Project 中有一个文件夹,比如 ED 文件夹,当我在 Eclipse 中指定在哪里查找我写入的文件时 File file = new File("ED/text.txt"); e
这是奇怪的事情,这个有效: $('#box').css({"backgroundPosition": "0px 250px"}); 但这不起作用,它只是不改变位置: $('#box').animate
这个问题在这里已经有了答案: Why does OR 0 round numbers in Javascript? (3 个答案) 关闭 5 年前。 Mozilla JavaScript Guide
这个问题在这里已经有了答案: Is the function strcmpi in the C standard libary of ISO? (3 个答案) 关闭 8 年前。 我有一个问题,为什么
我目前使用的是共享主机方案,我不确定它使用的是哪个版本的 MySQL,但它似乎不支持 DATETIMEOFFSET 类型。 是否存在支持 DATETIMEOFFSET 的 MySQL 版本?或者有计划
研究 Seam 3,我发现 Seam Solder 允许将 @Named 注释应用于包 - 在这种情况下,该包中的所有 bean 都将自动命名,就好像它们符合条件一样@Named 他们自己。我没有看到
我知道 .append 偶尔会增加数组的容量并形成数组的新副本,但 .removeLast 会逆转这种情况并减少容量通过复制到一个新的更小的数组来改变数组? 最佳答案 否(或者至少如果是,则它是一个错
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
noexcept 函数说明符是否旨在 boost 性能,因为生成的对象中可能没有记录异常的代码,因此应尽可能将其添加到函数声明和定义中?我首先想到了可调用对象的包装器,其中 noexcept 可能会产
我正在使用 Angularjs 1.3.7,刚刚发现 Promise.all 在成功响应后不会更新 angularjs View ,而 $q.all 会。由于 Promises 包含在 native
我最近发现了这段JavaScript代码: Math.random() * 0x1000000 10.12345 10.12345 >> 0 10 > 10.12345 >>> 0 10 我使用
我正在编写一个玩具(物理)矢量库,并且遇到了 GHC 坚持认为函数应该具有 Integer 的问题。是他们的类型。我希望向量乘以向量以及标量(仅使用 * ),虽然这可以通过仅使用 Vector 来实现
PHP 的 mail() 函数发送邮件正常,但 Swiftmailer 的 Swift_MailTransport 不起作用! 这有效: mail('user@example.com', 'test
我尝试通过 php 脚本转储我的数据,但没有命令行。所以我用 this script 创建了我的 .sql 文件然后我尝试使用我的脚本: $link = mysql_connect($host, $u
使用 python 2.6.4 中的 sqlite3 标准库,以下查询在 sqlite3 命令行上运行良好: select segmentid, node_t, start, number,title
我最近发现了这段JavaScript代码: Math.random() * 0x1000000 10.12345 10.12345 >> 0 10 > 10.12345 >>> 0 10 我使用
我是一名优秀的程序员,十分优秀!