Program to get input from user

As we all know,  programs are developed to do some functionality.

For an example, when developing a program to perform copy operation, that program would require an input from user to copy a file from that place to a given destination.

so two inputs from an user is required, for the program to perform the copy operation, that inputs are source file and destination. The way the input will be given to the program should be decided before even developing the program. The program needs to be developed according to the way that it will receive the input from user.

There are two ways that a program can receive input from user to perform a particular functionality.

Arguments

Arguments can be passed to a program while executing the program.

Ex:  copy.py /etc/passwd /tmp

As in the above example, copy.py is a program where '/etc/passwd' and '/tmp' is  arguments to the program.  The copy.py program can be developed to parse the arguments(understand arguments) and take them as input to perform the copy operation.

How the arguments are parsed and understood by the program?

Arguments would be parsed using an argument parser. In python there are several modules such as sys.argv, optparse, argparse and docopt etc.., any one among these modules could be used to parse arguments. docopt is a simple and yet powerful argument parser where as 'sys' module is available in python library by default and it can be used to parse arguments of a simple program.

raw_input()

A program can be developed to prompt the user to provide inputs required for the program to perform  a particular functionality.

Ex: 
source code: copy.py
    #!/usr/bin/env python
  #
  src = raw_input('Provide source file\n>')
  dest = raw_input('Provide destination\n>')

Output: 
$ python copy.py
       Provide source file
       >/etc/passwd
       Provide destination
       >/tmp

From the above example, you would have understood that raw_input() built in function can be used to prompt for an input from user.

A program developed using this method becomes user interactive program, a user should be available to provide inputs to the program after executing it.


Conclusion:

Arguments is useful when it comes to automation as the program itself a non interactive program as it receives required inputs while executing it. Where as raw_input method receives input to the program from user after executing the program, hence a user should be present to provide the required inputs.





Post a Comment

0 Comments