Python command line file input stream

0 votes
I am a beginner in python coming from C/C++ background. So I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as:

python main.py < text.txt

Any help would be appreciated.
Feb 8, 2019 in Python by ana1504.k
• 7,910 points
1,759 views

1 answer to this question.

0 votes
You can use argparse to create an option parser that accepts a file path and opens it.

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type='open')
    args = parser.parse_args()

    for line in args.infile:
        print line

if __name__ == '__main__':
    main()
answered Feb 8, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

How to input optional arguments in python command line?

Please use this code. if len(sys.argv) == 2: first_log ...READ MORE

answered Jul 11, 2019 in Python by Suri
7,572 views
+1 vote
1 answer

Reading a large file, line by line in Python

The correct, fully Pythonic way to read ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 58,100 points
910 views
0 votes
1 answer

Enter a 1-10, each on a new line in a file - python

Try something like this: i=1 for i in range(10): ...READ MORE

answered Jun 20, 2019 in Python by Greg
646 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,352 views
0 votes
1 answer
0 votes
2 answers

In Python, how do I read a file line-by-line into a list?

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 580 points
1,718 views
0 votes
1 answer

How to read a large file, line by line, in Python?

The correct, fully Pythonic way to read ...READ MORE

answered Jul 1, 2019 in Python by SDeb
• 13,300 points
821 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP