简体   繁体   English

python的sys.stdin.read()会阻塞吗?

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

I'm adapting this Django management command for my own purposes. 我正在为我自己的目的调整这个Django管理命令 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. 该脚本是一个简单的while循环守护进程,它根据协议从sys.stdin(第152行,在command.handle() )读取并将结果写入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. 我希望sys.stdin.read()能够阻塞直到它收到一些东西,但我发现当我运行这个脚本时,它会在发送或接收任何数据之前吃掉100%的CPU。

  1. Does sys.stdin.read(n) block? sys.stdin.read(n)阻塞了吗?
  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? time.sleep(s)安全使用,或者我会错过输入或响应缓慢?

By default, sys.stdin.read() and sys.stdin.read(n) are blocking calls. 默认情况下, sys.stdin.read()sys.stdin.read(n)是阻塞调用。 I would assume the consumption of 100% CPU is actually attributable to streaming data into your script or some other behavior not cited here. 我认为100%CPU的消耗实际上可归因于流数据流入您的脚本或此处未引用的其他一些行为。

Upon looking at the help documentation for sys.stdin.read , I noticed this: 在查看sys.stdin.read的帮助文档sys.stdin.read ,我注意到了这一点:

read(...) 读(...)

read([size]) -> read at most size bytes, returned as a string. read([size]) - >读取最多大小字节,作为字符串返回。

If the size argument is negative or omitted, read until EOF is reached. 如果size参数为负数或省略,则读取直到达到EOF。 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. 它还让我在SO上追查类似的问题。 Voila: Non-blocking read on a subprocess.PIPE in python Voila: python中 subprocess.PIPE上的非阻塞读取

Good luck with your adaptation! 祝你好运!

It works OK on my machine (ie blocks with negligent CPU usage while it's reading) - can you check it from a simple command line script before? 它在我的机器上运行正常(即在读取时CPU使用率过低的块) - 您可以在之前通过简单的命令行脚本进行检查吗? Also, I tested this within Linux, might be different on other platforms. 另外,我在Linux中对此进行了测试,在其他平台上可能会有所不同。

流是否有可能已关闭(例如EOF已发送)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM