python中sys.stdin_python的sys.stdin.read()块?

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.

Does sys.stdin.read(n) block?

If not, how can I make this daemon more polite?

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值