Me All
Me All

Reputation: 269

Reading a text file from standard input using <

I have a Python script which ends the following way:

if __name__ == "__main__":
     if len(sys.argv) == 2:
       file = open(sys.argv[1])
       text = file.readline()
       ... #more statements

This works when I type in the following: $ python3 script.py my_file.txt

However, I want to change it so my script can accept text from standard input (or even a text file). This is what I want to be able to do:

$ ./script.py < my_file.txt

I think I need to use sys.stdin.read() (or maybe sys.stdin.readlines()). Could you tell me what I would need to change from my original script?

I'm sorry if this looks very basic, but I'm new to Python and I find it hard to see the difference.

Upvotes: 0

Views: 50

Answers (2)

LeKhan9
LeKhan9

Reputation: 1350

Theres a cool module you can use for this! Assuming you want to do processing per line:

import fileinput

for line in fileinput.input():
    process_line(line)

Upvotes: 0

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

It's exactly what you said, you don't need to open a file.

Instead of calling file.readline(), call sys.stdin.readline().

You can make it "nice", with something like:

file = sys.stdin if use_stdin else open(sys.argv[1])

Upvotes: 1

Related Questions