samedi 25 avril 2015

If there is no command-line argument, read stdin Python

So I have a text file called ids that looks like this:

15 James
13 Leon
1 Steve
5 Brian

And my Python program (id.py) is supposed to read the file name as a command-line argument, put everything in a dictionary where the IDs are the keys, and print the output sorted numerically by IDs. This is the expected output:

1 Steve
5 Brian
13 Leon
15 James

I got it working for this part (calling on terminal python id.py ids). However, now I am supposed to check if there is no arguments, it will read stdin (for example, python id.py < ids), and eventually print out the same expected output. However, it crashes right here. This is my program:

entries = {}

file;

if (len(sys.argv) == 1):
      file = sys.stdin
else:
      file = sys.argv[-1] # command-line argument

with open (file, "r") as inputFile:
   for line in inputFile: # loop through every line
      list = line.split(" ", 1) # split between spaces and store into a list

      name = list.pop(1) # extract name and remove from list
      name = name.strip("\n") # remove the \n
      key = list[0] # extract id 

      entries[int(key)] = name # store keys as int and name in dictionary

   for e in sorted(entries): # numerically sort dictionary and print 
      print "%d %s" % (e, entries[e])

Aucun commentaire:

Enregistrer un commentaire