Search code examples
pythonargvraw-input

argv vs. raw_input


I know that when using argv I have to type the file as an argument (ex: python ex15.py ex15_sample.txt) and when using raw_input I enter the filename as an input.

But I can't seem to find out why one way of getting the filename would be better than another. Can someone explain why?


Solution

  • That's because you generally should avoid interactive user input if it's not a key feature. In your example: Reading from stdin or the command line allows to combine different programs and run them in scripts and so on.

    Imagine you execute a lot of code and sit in front of the screen waiting for the input request to come. Wasn't it better to specify all relevant information on the command line and to go and prepare a cup of coffee instead?

    What you could do:

    • Check if len(argv) > 1
    • If so, use argv[1] as the file name
    • If not, ask the user.

    This adds a nice feature to your program: You can either specify the file name on the command line or enter it in an interactive mode.

    Try this:

    try:
        fn = argv[1]
    
    except IndexError:
        fn = raw_input("filename > ")