简体   繁体   中英

Python3: Threadsafe mechanisms to redirect stdin, stdout, stderr

I'm attempting to redirect stdin, stdout, and stderr of a debugged program in python, and quickly saw that other people have had success by assigning StringIO instances to sys.stdin/out/err.

However, the debugged program is in one thread, while the StringIO instances are being written to and read from using a different thread. No documentation that I can find describes StringIO objects as being thread safe, and while I can wrap my own read/write calls in locks, I don't think I can force the debugged programs to use those same locks.

How can I force StringIO to do what I want? Otherwise, what will do what I want?

Edit: As requested an example of an anticipated race condition is as follows:

let's say I'm reading from stdout. I read the StringIO's full contents, and then flush the object... except that between my read and flush operations, the debugged program has printed more information, which also ends up getting flushed. In other words, I'm losing some of the information.

Edit 2: I found another question essentially asking the same question , but his answer doesn't seem very pythonic, so I'm leaving this open

I ran into the answer while skimming through Qdb 's source code. This implementation reassigns stdin , stdout , and stderr to self , and implements the following file-like functions:

close
encoding
isatty
flush
writelines
write
readlines
readline

Now, because all of the io functions are within your class (assuming you're using a class), you can control synchronization all day long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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