Does python block sys.stdin.read ()?

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

I would expect sys.stdin.read() be locked until it gets something, but I found that when I run this script, it eats up to 100% of the CPU before any data is sent or received .

  • Does sys.stdin.read(n) ?
  • If not, how to make this demon more polite?
  • Is time.sleep(s) safe to use, or will I skip input or will not respond?
+4
source share
3 answers

By default, sys.stdin.read() and sys.stdin.read(n) block calls. I would suggest that consuming 100% of the CPU is actually related to streaming data to your script, or some other behavior not listed here.

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

read (...)

read ([size]) β†’ read no more than size bytes, return as a string.

If the size argument is negative or skipped, read until EOF is reached. Please note that in non-blocking mode, less data than requested can be returned even if the size parameter is not specified.

(Emphasize mine.)

This means that lock mode is the default behavior that matches my experience. It also led me to search for similar questions on SO. Voila: Non-blocking reading on .PIPE subprocess in python

Good luck in adapting!

+2
source

It works fine on my machine (i.e. blocks with CPU misuse when reading) - can you check it from a simple command line script before? Also, I tested this on Linux, maybe different on other platforms.

+1
source

Is there a chance that the thread has been closed (e.g. EOF sent)?

0
source

All Articles