0

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.

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Would I still need to leave if len(sys.argv) == 2:? Or can I delete this part?
It may be that the flag use_stdin should be len(sys.argv) != 2 ;) The flag should be whatever you need to decide between file input or standard input.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.