python的sys.stdin.read()块? [英] Does python's sys.stdin.read() block?

查看:693
本文介绍了python的sys.stdin.read()块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调整这个Django管理命令用于我自己的目的。脚本是一个简单的while循环守护程序,它根据 command.handle()) git.process-one.net/ejabberd/mainline/blobs/raw/2.1.x/doc/dev.html#htoc8rel =nofollow>协议,并将结果写入sys.stdout。 p>

我希望 sys.stdin.read()阻止,直到它收到东西,但是我发现当我运行这个脚本,在任何数据发送或接收之前,它会占用100%的CPU。


  1. sys.stdin

  2. 如果没有,我该如何让这个守护进程更有礼貌?

  3. time.sleep(s)安全使用,还是输入错误或响应迟缓?


解决方案

默认情况下, sys.stdin.read() sys.stdin。 read(n)正在阻止调用。我会假设100%的CPU的消耗实际上归因于流式传输数据到您的脚本或其他一些其他未被引用的行为。



查看帮助文档 sys.stdin.read ,我注意到:


read(...)



read([size]) - >读取大多数字节,以字符串形式返回。



如果size参数为负或省略,直到达到EOF。
请注意,在非阻塞模式下,数据少于请求的数量
可能会被返回,即使没有给出大小参数。


(重点是我的。)



这意味着阻止模式是默认行为,这符合我的经验。这也导致我跟踪关于SO的类似问题。 Voila:
非阻塞读取子流程.PIPE python



祝你好运!


I'm adapting this Django management command for my own purposes. The script is a simple while-loop daemon that reads from sys.stdin (line 152, in command.handle()) according to a protocol and writes results to sys.stdout.

I would expect sys.stdin.read() to block until it receives something, but I find that when I run this script, it eats up 100% CPU before any data has been sent or received.

  1. Does sys.stdin.read(n) block?
  2. If not, how can I make this daemon more polite?
  3. Is time.sleep(s) safe to use, or will I miss input or be slow to respond?

解决方案

By default, sys.stdin.read() and sys.stdin.read(n) are blocking calls. I would assume the consumption of 100% CPU is actually attributable to streaming data into your script or some other behavior not cited here.

Upon looking at the help documentation for sys.stdin.read, I noticed this:

read(...)

read([size]) -> read at most size bytes, returned as a string.

If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.

(Emphasis mine.)

This implies blocking mode is the default behavior, which is consistent with my experience. It also led me to track down similar questions on SO. Voila: Non-blocking read on a subprocess.PIPE in python

Good luck with your adaptation!

这篇关于python的sys.stdin.read()块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆