Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't < working to read in a file from the command line (simple Python code)?

I have a simple program that reads in numbers and returns them sorted:

import sys

myset = set()
arguments = sys.argv[1:]

for x in arguments:
    myset.add(int(x.rstrip()))


newset = sorted(myset)
print ("sorted")

for x in newset:
    print x

It works perfectly when I type "python pysortints.py 1 5 6 7 2 6 7 254 2 543", but when I try something like "python pysortints.py < testfile" (when testfile is lines of pure numbers), nothing comes out except some of the print statements ("sorted").

Any ideas? I tried rstrip on x just in case, but it didn't seem to do anything.

like image 771
Worcestershire Avatar asked Jun 16 '26 14:06

Worcestershire


1 Answers

When you do

pysortints.py < testfile

the contents of testfile becomes available in the standard input, not as the command line parameters.

So, you need to read the data with raw_input (if you are using Python 2.x) or input (if your are using Python 3.x) functions.

Or alternatively, you can read directly from the sys.stdin, like this

import sys
for x in sys.stdin:
    myset.add(int(x))

Note: You don't need to strip the string data being passed to int function. It will ignore the whitespace characters at the beginning and ending, for you :)

Lets improve the code a little bit. Your intention is to find only the unique elements and sort them. So, instead of adding elements to the set, you can use set comprehension, like this

{int(line) for line in sys.stdin}

This will get all the unique elements in int type. Next, you can simply apply sorted over this itself

print sorted({int(line) for line in sys.stdin})

If you want to print each and every line in new line, like you have done in your example, you can convert the sorted numbers to strings, using map and str function, like this

map(str, sorted({int(line) for line in sys.stdin}))

and then you can join them together with \n and print it, like this

print "\n".join(map(str, sorted({int(line) for line in sys.stdin})))

There you go! Your entire program in a single line. :) :)

like image 155
thefourtheye Avatar answered Jun 19 '26 04:06

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!