Python os.dup and side-effects [closed]
At the beginning of my python script I do:
if '-' in args:
fd = os.fdopen(os.dup(开发者_StackOverflow社区0))
sys.stderr.write(fd.read())
fd.close()
I thought that this wouldn't affect the behavior of the rest of my program but it seems to, i.e. if I comment out these 4 lines my code works but if they are executed then my program has unexpected results (which I'm having difficulty troubleshooting).
Am I using os.dup incorrectly?
Thanks.
You are not, alas, using os.dup()
correctly. Evidently you want to “look ahead” in the Standard Input stream to see what will be there, and print it out, but then have the rest of the program start up and see the same input still sitting there waiting on the Standard Input. (Is my guess correct that you are doing this for debugging purposes?)
The problem with your approach is that running os.dup()
simply creates a second file descriptor, not a second file — in other words, it creates another integer with which you can refer to the source of your input data, but dup()
does not create a second actual source of data. So whether you read()
from the first file descriptor or the second one, you have still “used up” all of the data from your input stream.
I also am not sure about the correct usage of os.dup()
, but for your example you could do
if '-' in args:
sys.stderr.write(sys.stdin.read())
or even
print(input()) # for python 2.x it would be print raw_input()
精彩评论