I was docked points in a coding challenge that specified that I needed to read from STDIN. This was my input method:
def __init__(self, input):
self._dictionary = {}
with open(input, 'r') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if self._dictionary.__contains__(row[0]):
self._dictionary[row[0]].append(row[1])
else:
self._dictionary.update({row[0]: row[1].split()})
and at the end of the script
if __name__ == "__main__":
script = Script(sys.argv[1])
for line in script.output_method():
print line
Was I wrong to use sys.argv in a challenge that asked to read from stdin? What's the difference? What should I have done to satisfy the requirements?
They are not the same:
>>> import sys
>>> sys.argv == sys.stdin
False
sys.argv
sys.stdin sys.stdout sys.stderr
As @Vivek Rai mentioned in the comments, you can use sys.stdin.readlines() to read from standard in. Also, fileinput, is available to you, which seems to do exactly what you want.
import fileinput
for line in fileinput.input():
process(line)
This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With