Take input from stdin in Python

The sys module in python helps us to access the variables maintained by the interpreter. It also provides functions to interact with the interpreter. To use sys in Python, we firstly import sys

import sys

There are a number of ways in which we can take input from stdin in Python.

  • sys.stdin
  • input()
  • fileinput.input()
  1. Using sys.stdin: sys.stdin can be used to get input from the command line directly. It used is for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import sys
      
      
    for line in sys.stdin:
        if 'q' == line.rstrip():
            break
        print(f'Input : {line}')
      
    print("Exit")

    chevron_right

    
    

    Output

  2. Using input(): input() can be used to take input from the user while executing the program and also in the middle of the execution.

    Example:



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # this accepts the user's input 
    # and stores in inp
    inp = input("Type anything")
      
    # prints inp
    print(inp)

    chevron_right

    
    

    Output:

  3. Using fileinput.input(): If we want to read more that one file at a time, we use fileinput.input() . There are two ways to use fileinput.input(). To use this method, first we need to import fileinput.

    1st method :
    Here, we pass the name of the files as a tuple in the “files” agrument. Then we loop over each file to read it.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import fileinput 
      
      
    with fileinput.input(files = ('sample.txt', 'no.txt')) as f:
        for line in f:
            print(line)

    chevron_right

    
    

    Output:

    2nd method :
    Here, we pass the file name a sys argument in the command line.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import fileinput 
      
      
    for f in fileinput.input():
        print(f)

    chevron_right

    
    

    Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.