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


so have text file called ids looks this:

15 james 13 leon 1 steve 5 brian 

and python program (id.py) supposed read file name command-line argument, put in dictionary ids keys, , print output sorted numerically ids. expected output:

1 steve 5 brian 13 leon 15 james 

i got working part (calling on terminal python id.py ids). however, supposed check if there no arguments, read stdin (for example, python id.py < ids), , print out same expected output. however, crashes right here. program:

entries = {}  file;  if (len(sys.argv) == 1):       file = sys.stdin else:       file = sys.argv[-1] # command-line argument  open (file, "r") inputfile:    line in inputfile: # loop through every line       list = line.split(" ", 1) # split between spaces , store list        name = list.pop(1) # extract name , remove list       name = name.strip("\n") # remove \n       key = list[0] # extract id         entries[int(key)] = name # store keys int , name in dictionary     e in sorted(entries): # numerically sort dictionary , print        print "%d %s" % (e, entries[e]) 

sys.stdin already-open (for reading) file. not file name:

>>> import sys >>> sys.stdin <open file '<stdin>', mode 'r' @ 0x7f817e63b0c0> 

so can use file object api.

you try this:

if (len(sys.argv) == 1):     fobj = sys.stdin else:     fobj = open(sys.argv[-1], 'r') # command-line argument  # ... use file object 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -