summaryrefslogtreecommitdiff
path: root/doc/source/index.rst
blob: ae85d918ad73b4c2911784da2cdf95145d93df21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Documentation
=============

.. toctree::
   :maxdepth: 2

   argparse-vs-optparse
   overview
   api-docs


Example usage
=============

The following simple example uses the argparse module to generate the command-line interface for a Python program that sums its command-line arguments and writes them to a log file::

  import argparse
  import sys
  
  if __name__ == '__main__':
  
      # create the parser    
      parser = argparse.ArgumentParser(
          description='Sum the integers on the command line.')
  
      # add the arguments    
      parser.add_argument(
          'integers', metavar='int', type=int, nargs='+',
          help='one of the integers to be summed')
      parser.add_argument(
          '--log', type=argparse.FileType('w'), default=sys.stdout,
          help='the file where the sum should be written '
               '(default: write the sum to stdout)')
  
      # parse the command line    
      args = parser.parse_args()
  
      # write out the sum
      args.log.write('%s\n' % sum(args.integers))
      args.log.close()


Assuming the Python code above is saved into a file called ``scriptname.py``, it can be run at the command line and provides useful help messages::

  $ scriptname.py -h
  usage: scriptname.py [-h] [--log LOG] int [int ...]
  
  Sum the integers on the command line.
  
  positional arguments:
    int         one of the integers to be summed
  
  optional arguments:
    -h, --help  show this help message and exit
    --log LOG   the file where the sum should be written (default: write the sum
                to stdout)


When run with the appropriate arguments, it writes the sum of the command-line integers to the specified log file::

  $ scriptname.py --log=log.txt 1 1 2 3 5 8
  $ more log.txt
  20