Why does the following print "False"?
test.py:
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
print(text == text_in_script)
Command line:
echo test | py -3 test.py
Because sys.stdin texts come with a new line character. It is more obvious when test.py is this:
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
print("Input: {}".format(text))
print("Script: {}".format(text_in_script))
print(text == text_in_script)
The solution would be to strip the new line character. The following will return "True":
import sys
if __name__ == "__main__":
for text in sys.stdin:
text_in_script = 'test'
# warning: rstrip() removes all whitespace; see rstrip() docs for alternatives
print(text.rstrip() == text_in_script)
line.rstrip("\n") instead (note: it is portable if Python uses universal newlines mode (it does by default))