Python C program subprocess hangs at ""for line in iter""
You are trying to read the output from a C program using subprocess.Popen in Python, but the process is hanging at the line "for line in iter(process.stdout.readline, '')". This is a known issue with subprocess, and it is caused by buffering of the stdout stream.
Fix stdout buffer in C program directly
The stdout stream is buffered by default. This means that the C program will not send any output to the pipe until the buffer is full. To fix this, you can use the setvbuf function to set the stdout stream to line buffered. This will cause the C program to send output to the pipe immediately after each line is written.
Or use pseudo-TTY
Another option is to use a pseudo-TTY (terminal device) to communicate with the C program. This will allow the C program to send output to the pipe immediately, even if the stdout stream is buffered.
Or fix it without modifying the source of C program
Finally, you can use the stdbuf utility to change the buffering type without modifying the source code of the C program. This utility will allow you to force the C program to send output to the pipe immediately, even if the stdout stream is buffered.
The above is the detailed content of Why Does My Python Subprocess Hang When Reading C Program Output?. For more information, please follow other related articles on the PHP Chinese website!