Error argument expected one argument

Argparse TutorialВ¶ This tutorial is intended to be a gentle introduction to argparse , the recommended command-line parsing module in the Python standard library. There are two other modules that fulfill the same task, namely getopt (an equivalent for getopt() from the C language) and the deprecated optparse . Note also that argparse is […]

Содержание

  1. Argparse Tutorial¶
  2. Concepts¶
  3. The basics¶
  4. Introducing Positional arguments¶
  5. Argument -p: expected one argument #63
  6. Comments
  7. argparse: expected one argument when passing a negative value
  8. 3 Answers 3
  9. Argparse: expected one argument
  10. 2 Answers 2
  11. Related
  12. Hot Network Questions
  13. Subscribe to RSS
  14. Processing arguments for subprocesses using argparse: «Expected one argument»
  15. 3 Answers 3

Argparse Tutorial¶

This tutorial is intended to be a gentle introduction to argparse , the recommended command-line parsing module in the Python standard library.

There are two other modules that fulfill the same task, namely getopt (an equivalent for getopt() from the C language) and the deprecated optparse . Note also that argparse is based on optparse , and therefore very similar in terms of usage.

Concepts¶

Let’s show the sort of functionality that we are going to explore in this introductory tutorial by making use of the ls command:

A few concepts we can learn from the four commands:

The ls command is useful when run without any options at all. It defaults to displaying the contents of the current directory.

If we want beyond what it provides by default, we tell it a bit more. In this case, we want it to display a different directory, pypy . What we did is specify what is known as a positional argument. It’s named so because the program should know what to do with the value, solely based on where it appears on the command line. This concept is more relevant to a command like cp, whose most basic usage is cp SRC DEST . The first position is what you want copied, and the second position is where you want it copied to.

Now, say we want to change behaviour of the program. In our example, we display more info for each file instead of just showing the file names. The -l in that case is known as an optional argument.

That’s a snippet of the help text. It’s very useful in that you can come across a program you have never used before, and can figure out how it works simply by reading its help text.

The basics¶

Let us start with a very simple example which does (almost) nothing:

Following is a result of running the code:

Here is what is happening:

Running the script without any options results in nothing displayed to stdout. Not so useful.

The second one starts to display the usefulness of the argparse module. We have done almost nothing, but already we get a nice help message.

The —help option, which can also be shortened to -h , is the only option we get for free (i.e. no need to specify it). Specifying anything else results in an error. But even then, we do get a useful usage message, also for free.

Introducing Positional arguments¶

And running the code:

Here is what’s happening:

We’ve added the add_argument() method, which is what we use to specify which command-line options the program is willing to accept. In this case, I’ve named it echo so that it’s in line with its function.

Calling our program now requires us to specify an option.

The parse_args() method actually returns some data from the options specified, in this case, echo .

The variable is some form of ‘magic’ that argparse performs for free (i.e. no need to specify which variable that value is stored in). You will also notice that its name matches the string argument given to the method, echo .

Note however that, although the help display looks nice and all, it currently is not as helpful as it can be. For example we see that we got echo as a positional argument, but we don’t know what it does, other than by guessing or by reading the source code. So, let’s make it a bit more useful:

Now, how about doing something even more useful:

Источник

Argument -p: expected one argument #63

Facing the error below while trying to compile;

D:xampphtdocsprotestoneusage: jasperstarter process [-h] -f [ . ] [-o ] [-w]
[-a []] [-P [ . ]]
[-r []] [-t ] [-H ]
[-u ] [-p ] [-n ]
[—db-sid ] [—db-port ]
[—db-driver ] [—db-url ]
[—jdbc-dir

] [—data-file ]
[—csv-first-row] [—csv-columns ]
[—csv-record-del ]
[—csv-field-del ]
[—csv-charset ] [—xml-xpath ]
[—json-query ] [-N ] [-d]
[-s ] [-c ]
[—out-field-del ]
[—out-charset ]
jasperstarter: error: argument -p: expected one argument
PHP Fatal error: Uncaught exception ‘JasperPHPExceptionErrorCommandExecutable’ with message ‘Your report has an error and couldn ‘t be processed! Try to output the command using the functi
on output(); and run it manually in the console.’ in D:xampphtdocsprotestonevendorgeekcomphpjaspersrcJasperPHP.php:198
Stack trace:
#0 D:xampphtdocsprotestonereport.php(52): JasperPHPJasperPHP->execute()
#1


thrown in D:xampphtdocsprotestonevendorgeekcomphpjaspersrcJasperPHP.php on line 198

Fatal error: Uncaught exception ‘JasperPHPExceptionErrorCommandExecutable’ with message ‘Your report has an error and couldn ‘t be processed! Try to output the command using the function o utput(); and run it manually in the console.’ in D:xampphtdocsprotestonevendorgeekcomphpjaspersrcJasperPHP.php:198
Stack trace:
#0 D:xampphtdocsprotestonereport.php(52): JasperPHPJasperPHP->execute()
#1


thrown in D:xampphtdocsprotestonevendorgeekcomphpjaspersrcJasperPHP.php on line 198

The text was updated successfully, but these errors were encountered:

Источник

argparse: expected one argument when passing a negative value

I’m trying to pass a parameter which is a list of values:

For most cases, this code works as expected:

  • python test.py —cb_ticks «1» -> 1
  • python test.py —cb_ticks «1,2» -> 1,2
  • python test.py —cb_ticks «-1» -> -1

But when I’m trying to pass more than one value, where the first is negative:

I’m getting the following error: test.py:

error: argument —cb_ticks: expected one argument

3 Answers 3

The add_argument method allows you to tell the argument parser to expect multiple (or no) values:

but the values are expected to be space separated, so you’ll have to execute your script as:

To accept the inputs as specified in the question, you must pre-process the arguments. I tried many things, from where the negative number issue appears in the documentation, from here and from Python Argparse: Issue with optional arguments which are negative numbers, but those methods didn’t work in this specific kind of case (my case was https://github.com/poikilos/minetestmapper-python/blob/master/minetestmapper-numpy.py). I solved the issue as follows.

Step 1: Before using argparse, do the following:

Step 2: Use argpase as normal except don’t use it for any non-numerical argument that starts with a hyphen:

Step 3: Split your argument manually then add it to your args dict:

Alternatively:

If you were using the parser directly instead of using vars like in the question, (do #1 as I described) then in #2 change args = vars(parser.parse_args()) to args = parser.parse_args() , then for #3 instead do:

Step 3: Split your argument manually then add it to an args object:

Источник

Argparse: expected one argument

I have argparse arguments setup in the following fashion:

However, when I run script.py -k kindledx http://url.com , I get the following error: gallery2kindle.py: error: argument -k: expected one argument

Wasn’t an argument called when I used ‘kindledx’ after flag ‘-k’?

2 Answers 2

Wasn’t an argument called when I used ‘kindledx’ after flag ‘-k’?

It was, and if you add a print args after args = parser.parse_args() , you can see the parsing works:

but in this line

you don’t pass an argument to k. Compare

Since this is the first result of googling this error, I want to share that it can happen if you follow advice to compatible with Windows / in Linux:

This causes -option /path/path throws expected one argument even though it looks like valid. You need quotes it to be -option ‘/path/path’ or remove the / in the prefix_chars above to fix it.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Processing arguments for subprocesses using argparse: «Expected one argument»

First of all, I am sorry about the title that does not give a perfect idea of what my problem is, I kinda struggled with it, so I am going to illustrate it more clearly with a reproducible example:

I have the following code:

example.py:

The —extra_args argument is then going to be used as a positional argument for a subprocess call.

The argument I need to pass is the following one: —repeat=0 . It does not work, I got the following results:

What I understand is that the parser process the —repeat as an argument, find no value for it, and breaks. But unfortunately I have no choice than to write ‘—repeat=0’ all attached, because of the software receiving it.

Would you know any workaround around it ?

3 Answers 3

It seems there is a problem with the way parse_args inteprets the double dash at the beginning of the arg string.

If you add a prefix, it could be a single character, like a space within the string, this could be a workaround.

It would be easy then in your code to strip the extra_args of the first character or whatever prefix.

Not ideal but an easy workaround.

Handling values that start with a ‘—‘ is a challenge with argparse . The idea that it marks a flag (as with your —extra_args ) is so integral to argparse , that it’s hard to work around it.

Simply adding quotes doesn’t help. They control how the shell handles the strings, but doesn’t otherwise change what’s in sys.argv .

describes the use of pseudo-argument «—«, but that only works for positional arguments. (I’d have to look at the code again to see why it doesn’t do anything with optionals.)

There is a nargs=argparse.REMAINDER that works like the pseudo-argument, but again only for positionals. And there are some problem with using it, so it’s now undocumented.

Adding spaces such as in » —repeat = 0″ has been mentioned in previous SO about the topic.

Источник

Related Searches: Python argparse, Python arguments, Python optional arguments, Python positional arguments, python argumentparser, python argparse example, python argparse boolean, python script arguments, python argparse list

In this tutorial we will explore argparse module from Python programming language. I will share multiple examples with different scenarios to use python argparse to process command line arguments. Now these input command line arguments can be optional or in the for of array of any other format. So our code must handle these accordingly.

What is command line argument?

Before we go ahead you should be familiar with the concept of command line arguments. Let us take a very simple example which I am sure you must have used in your career while working on Linux:

[root@server scripts]# ls -ltr /var/log/
total 1628
-rw-r--r--. 1 root root    489 Nov  7  2019 grubby_prune_debug
-rw-------. 1 root root  12174 May 25  2020 yum.log-20200525
-rw-------. 1 root root      0 Jul 23  2020 spooler-20210319
-rw-------. 1 root root    194 Mar 19 14:39 maillog-20210319
-rw-------. 1 root root   7880 Mar 19 15:06 yum.log-20210319
-rw-------. 1 root root 165274 Mar 19 15:12 messages-20210319
-rw-------. 1 root root  13106 Mar 19 15:12 secure-20210319
-rw-------. 1 root root   2948 Mar 19 15:46 cron-20210319
...

Here we are using ls command used to list files and directories. Along with the ls command I have used some command line arguments i.e. -ltr which can also be used separately or in different order ls -l -t -r /var/log and you should still get the same output.

ALSO READ: Python Compare Strings [10+ Examples]

You may also notice that ls command works just fine without these input arguments, which means that these are all optional arguments. We can add these arguments to further refine the command output.

Similarly when we write a python script, we may have a requirement to support command line arguments to collect different values. We will explore this further using different examples.

Overview on python argparse

Python’s standard library module for interpreting command-line arguments, argparse, supplies a host of features, making it easy to add argument handling to scripts in a fashion that is consistent with other tools. You can make arguments required or optional, have the user supply values for certain arguments, or define default values. argparse creates usage text, which the user can read using the —help argument, and checks the user-supplied arguments for validity.

Using argparse is a four-step process.

  • Create a parser object.
  • Add arguments your program accepts to the parser object.
  • Tell the parser object to parse your script’s argv (short for argument vector, the list of arguments that were supplied to the script on launch); it checks them for consistency and stores the values.
  • Use the object returned from the parser object in your script to access the values supplied in the arguments.

The default syntax to use ArgumentParser object from python argparse is:

argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)

Example-1: Create help or usage section

In this example we will create a basic help or usage section using python argparse. By default add_help is enabled with ArgumentParser so you can just execute the following code which will add a help section with an optional argument of -h or --help:

#!/usr/bin/env python3

import argparse

## You could also use
## parser = argparse.ArgumentParser(add_help=True)
parser = argparse.ArgumentParser()

parser.parse_args()

Output from this script:
Python argparse (ArgumentParser) examples for beginners

ALSO READ: Numpy random Examples | rand() | randint() function

Example-2: Parse argument without value

In this example we will pass certain options to our script which do not expect any value. For example use -v or --verbose to enable verbose output or use -q or —quiet to suppress the output. Now these are optional arguments and do not require a value. The presence or absence of the option determines the appropriate Boolean in the parser.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-q', '--quiet',
                    action='store_true',
                    dest='quiet',
                    help='Suppress Output'
                    )
parser.add_argument('-v', '--verbose',
                    action='store_true',
                    help='Verbose Output'
                    )
args = parser.parse_args()

print('Quiet mode is %r.' % args.quiet)

We have defined our action variable as store_true, which is the reason why the parser will not expect a value. You can read more about action in Example-10 of this article.

Most options do not need an action to be specified (the default is store, which stores the value it receives). The specification of store_true or store_false is the most common way to indicate that an option is a flag and should not accept a value.

The dest keyword argument determines how to look up the parsed value (in this case, True or False) on the object you get back when you call parse_args. The string used here will be the attribute name on the object. In many cases, the dest keyword argument is optional.

ArgumentParser determines an intuitive name based on the name of the option itself. However, it is useful to explicitly provide this for readability and maintainability.

Output from this script with different optional arguments:

~]# python3 eg-2.py -h
usage: eg-2.py [-h] [-q] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -q, --quiet    Suppress Output
  -v, --verbose  Verbose Output

~]# python3 eg-2.py -v
Quiet mode is False.

~]# python3 eg-2.py -q
Quiet mode is True.

ALSO READ: Learn python *args and **kwargs with simple examples

Example-3: Use different prefix for command line arguments

Normally in Linux and Uni we use single (-) or double hyphen (--) as the prefix for all the command line arguments. But for Windows we prefer forward slash (or simply slash) character (/).

You can change which characters are used for prefixes by providing the prefix_chars keyword argument to the ArgumentParser constructor, as shown here:

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser(prefix_chars='/')
parser.add_argument('/q', '//quiet',
                    action='store_true',
                    dest='quiet',
                    help='Suppress Output'
                    )
args = parser.parse_args()
print('Quiet mode is %r.' % args.quiet)

In this example, we changed the prefix character to /. Note that this also means that the argument itself (the one passed to add_argument) must change accordingly. Calling this script is still straightforward. You simply must use /q or //quiet (rather than -q or --quiet).

Output from this script:
Python argparse (ArgumentParser) examples for beginners

Example-4: Pass single value to python argument

We already defined an option flag which doesn’t expect any value by using store_true for action keyword in Example-2 above. Here we have not defined any action so by default it would expect a value for the input argument.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host',
                    default='localhost',
                    dest='host',
                    help='Provide destination host. Defaults to localhost',
                    type=str
                    )
args = parser.parse_args()
print(f'The host is "{args.host}"')

The script expects -H or --host argument with a single value which will be considered as destination host. We have defined a default value so that if we don’t define a host then localhost will be considered as the default destination. Additionally we are also using type keyword to convert the input argument value to string type.

ALSO READ: Python pwd module Explained [Practical Examples]

Here we are executing our sample script with different values using -H option:
Python argparse (ArgumentParser) examples for beginners

Example-5: Pass multiple values in single argument

In the previous example we were passing single value to -H input argument. Let’s see, what would happen if I pass no value or more than one values to -H:

~]# python3 eg-4.py -H
usage: eg-4.py [-h] [-H HOST]
eg-4.py: error: argument -H/--host: expected one argument

~]# python3 eg-4.py -H host1 host2
usage: eg-4.py [-h] [-H HOST]
eg-4.py: error: unrecognized arguments: host2

So as expected, our parser argument fails to handle multiple values. You can set an option to accept an unbound number of arguments, or an exact number by using the nargs keyword argument to add_argument.

In this example section we will cover following scenarios:

  • Argument expects exactly 2 values
  • Argument expects 1 or more values
  • Argument expects 0 or more values

Scenario-1: Argument expects exactly 2 values

In this example we will write a script which expects an argument with exactly two values.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--range',
                    default=[1-100],
                    dest='range',
                    help='Define the range. Default is 1-100',
                    type=int,
                    nargs=2
                    )
args = parser.parse_args()
print(f'The defined range is {args.range[0]}-{args.range[1]}')

This script expects --range argument which should have exactly 2 values. The input values will be converted to integer type. Using nargs=2 we are restricting the number of values for --range to exactly 2. Additionally we have also defined a default range value from 1-100.

Let us try this script with different values:

~]# python3 eg-5-scenario-1.py -h
usage: eg-5-scenario-1.py [-h] [--range RANGE RANGE]

optional arguments:
  -h, --help           show this help message and exit
  --range RANGE RANGE  Define the range. Default is 1-100

~]# python3 eg-5-scenario-1.py --range 5 100
The defined range is 5-100

~]# python3 eg-5-scenario-1.py --range 5
usage: eg-5-scenario-1.py [-h] [--range RANGE RANGE]
eg-5-scenario-1.py: error: argument --range: expected 2 arguments

~]# python3 eg-5-scenario-1.py --range 5 100 101
usage: eg-5-scenario-1.py [-h] [--range RANGE RANGE]
eg-5-scenario-1.py: error: unrecognized arguments: 101

As expected when we try to give more than or less than 2 values to --range argument, the script throws error because we have restricted the number of values to 2 using nargs.

ALSO READ: HackerRank Solution: Python Reduce Function [3 Methods]

Scenario-2: Argument expects 1 or more values

You can use the + value with nargs which indicates that the option expects one or more values to be provided. Let us look at this example where we will perform addition using all the values provided to --num argument.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--num',
                    dest='num',
                    help='Define integers to perform addition',
                    type=int,
                    nargs='+'
                    )
args = parser.parse_args()
print('%s = %d' % (
        ' + '.join([str(i) for i in args.num]),
        sum(args.num),))

Here we have defined nargs='+' for --num argument which means --num expects one or more values.

Let us execute this script with one or more values for --num argument:

~]# python3 eg-5-scenario-2.py --num 2
2 = 2

~]# python3 eg-5-scenario-2.py --num 2 3
2 + 3 = 5

~]# python3 eg-5-scenario-2.py --num 2 4 6 7
2 + 4 + 6 + 7 = 19

~]# python3 eg-5-scenario-2.py --num
usage: eg-5-scenario-2.py [-h] [--num NUM [NUM ...]]
eg-5-scenario-2.py: error: argument --num: expected at least one argument

~]# python3 eg-5-scenario-2.py -h
usage: eg-5-scenario-2.py [-h] [--num NUM [NUM ...]]

optional arguments:
  -h, --help           show this help message and exit
  --num NUM [NUM ...]  Define integers to perform addition

Scenario-3: Argument expects 0 or more values

Similar to (+) sign, you can use asterisk (*) with nargs to define zero or more values to a certain argument. We will update our script from Scenario-2 to use nargs='*' for --num argument and re-run the script:

~]# python3 eg-5-scenario-3.py --num
 = 0

~]# python3 eg-5-scenario-3.py --num 1 2 3
1 + 2 + 3 = 6

So now our script doesn’t fail when we don’t provide any value to --num argument.

ALSO READ: Python Deleter Property Decorators

Example-6: Pass mandatory argument using python argparse

In all our previous examples we were passing optional arguments to our python script. To pass a mandatory argument, you must use required keyword with True flag i.e. required=True.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--sleep',
                    required=True,
                    default=20,
                    dest='sleep',
                    help='Provide sleep timer',
                    type=int
                    )
args = parser.parse_args()

print('Provided sleep value is %r.' % args.sleep)

You may observe that when we execute this script and verify that -s or --sleep is required argument now.

~]# python3 eg-6.py
usage: eg-6.py [-h] -s SLEEP
eg-6.py: error: the following arguments are required: -s/--sleep

Although if you check the help section, -s or --sleep is shown under optional arguments section.

This is by design as parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). To overcome this you can parse the arguments and store into two different objects.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()

# Create a new group to store required arguments
requiredName = parser.add_argument_group('required named arguments')

# Add required arguments to the parser
requiredName.add_argument('-s', '--sleep',
                    required=True,
                    default=20,
                    dest='sleep',
                    metavar='TIME',
                    help='Provide sleep timer',
                    type=int
                    )

# Add optional arguments to the parser
parser.add_argument('-q', '--quiet',
                    action='store_true',
                    dest='quiet',
                    help='Suppress Output'
                    )

args = parser.parse_args()

print('Provided sleep value is %r.' % args.sleep)

Output from this script:
Python argparse (ArgumentParser) examples for beginners

Example-7: Pass multiple choices to python argument

Python ArgumentParser adds the capability to specify that an option may only be one of an enumerated set of choices. These can be handled by passing a container object as the choices keyword argument to add_argument(). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:

This script expects any of the three values between blue, black and brown for --color argument. The default value would be blue if --color argument is not defined.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--color',
                    choices=('blue', 'black', 'brown'),
                    dest='color',
                    default='blue',
                    help='Guess my lucky color'
                    )
args = parser.parse_args()
print('You have chosen %r.' % args.color)

Let us execute this script with different values for --color argument:

~]# python3 eg-7.py -h
usage: eg-7.py [-h] [--color {blue,black,brown}]

optional arguments:
  -h, --help            show this help message and exit
  --color {blue,black,brown}
                        Guess my lucky color
~]# python3 eg-7.py
You have chosen 'blue'.

~]# python3 eg-7.py --color red
usage: eg-7.py [-h] [--color {blue,black,brown}]
eg-7.py: error: argument --color: invalid choice: 'red' (choose from 'blue', 'black', 'brown')

ALSO READ: How to create, read, append, write to file in Python

Example-8: Pass positional arguments with python argparse

With python argparse, you must declare your positional arguments explicitly. If you do not, the parser expects to have no arguments left over after it completes parsing, and it raises an error if arguments still remain.

How do we define optional and positional arguments?

The declaration for positional arguments is equivalent to the declaration for options, except that the leading hyphen is omitted.
When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional.

For example, an optional argument could be created like:

>>> parser.add_argument('-f', '--foo')

while a positional argument could be created like:

>>> parser.add_argument('bar')

We will use the same code as we used in Example-5 to demonstrate nargs keyword. This script will expect integers as positional arguments which can be one or more. We will perform a SUM operation on these provided integers. We are explicitly converting the provided values into integers using type=int.

The code we used is mostly the same, except that the --num argument has been replaced with num, without the double-hyphen prefix.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('num',
                    nargs='+',
                    type=int,
                    help='Provide integers to perform SUM'
                    )
args = parser.parse_args()

print('%s = %d' % (' + '.join([str(i) for i in args.num]),
        sum(args.num),))

You can see that there is a new section of positional arguments in the help section now:
Python argparse (ArgumentParser) examples for beginners

ALSO READ: Python sort list [2 Methods and 8 Examples]

We can now execute our script without num argument:

~]# python3 eg-8.py 1 2 3
1 + 2 + 3 = 6

Example-9: Read a file as an input to python arguments

The Python argparse module provides a special class that can be sent to the type keyword argument of add_argument, which is argparse.FileType.

The argparse.FileType class expects the arguments that would be sent to Python’s open function, excluding the filename (which is what is being provided by the user invoking the program). If you are opening the file for reading, this may be nothing. open defaults to opening files only for reading. However, any arguments after the initial positional argument to open can be provided to FileType, and they will be passed on to open.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--file',
                    type=argparse.FileType('r'),
                    dest='myfile',
                    default='/tmp/file',
                    help='The config file to use'
                    )
args = parser.parse_args()
print(args.myfile.read())

This would read from /tmp/file by default, but allow you to specify a different file to read from using the --file argument. Rather than providing these options as text and forcing you to open the file yourself, you will simply be provided with an open file object:

~]# python3 eg-9.py
This is a test file

You may overwrite the default option by using --file argument:

~]# python3 eg-9.py --file /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.43.31   server1 server1.example.com

Following is the help section:

~]# python3 eg-9.py -h
usage: eg-9.py [-h] [--color MYFILE]

optional arguments:
  -h, --help      show this help message and exit
  --color MYFILE  The config file to use

ALSO READ: Python dictionary (15 easy examples with syntax)

Example-10: Using “action” with ArgumentParser

ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args().

Any of six built-in actions can be triggered when an argument is encountered:

  • store: Save the value, after optionally converting it to a different type. This is the default action taken if none is specified explicitly.
  • store_const: Save a value defined as part of the argument specification, rather than a value that comes from the arguments being parsed. This is typically used to implement command-line flags that are not boolean values.
  • store_true/store_false: Save the appropriate boolean value. These actions are used to implement Boolean switches.
  • append: Save the value to a list. Multiple values are saved if the argument is repeated.
  • append_const: Save a value defined in the argument specification to a list.
  • version: Print the version details about the program and then exit.

In this example we have defined all the possible actions which can be used with ArgumentParser():

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value')
parser.add_argument('-c', action='store_const', dest='constant_value', const='value-to-store', help='Store a constant value')
parser.add_argument('-t', action='store_true', default=False, dest='boolean_t', help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=True, dest='boolean_f', help='Set a switch to false')
parser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list')
parser.add_argument('-A', action='append_const', dest='const_collection', const='value-1-to-append', default=[], help='Added different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection', const='value-2-to-append', help='Add different values to list')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')

results = parser.parse_args()
print('simple_value     = {!r}'.format(results.simple_value))
print('constant_value   = {!r}'.format(results.constant_value))
print('boolean_t        = {!r}'.format(results.boolean_t))
print('boolean_f        = {!r}'.format(results.boolean_f))
print('collection       = {!r}'.format(results.collection))
print('const_collection = {!r}'.format(results.const_collection))

Following is our help section:
Python argparse (ArgumentParser) examples for beginners

ALSO READ: Python os.path.join() method [Practical Examples]

‘store’ — This just stores the argument’s value. This is the default action. For example:
Python argparse (ArgumentParser) examples for beginners

‘store_const’ — This stores the value specified by the const keyword argument.
Python argparse (ArgumentParser) examples for beginners

‘store_true’ and ‘store_false’ — These are special cases of ‘store_const’ used for storing the values True and False respectively.
Python argparse (ArgumentParser) examples for beginners

‘append’ — This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.
Python argparse (ArgumentParser) examples for beginners

‘append_const’ — This stores a list, and appends the value specified by the const keyword argument to the list.
Python argparse (ArgumentParser) examples for beginners

‘version’ — This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked

~]# python3 eg-10.py --version
eg-10.py 1.0

Summary

In this Python programming tutorial we learned about argparse module and it’s usage to create help section. The argparse modules provide very good support for reading data from the ­command line for Python programs that need to do this. The argparse module supersedes optparse module.

The argparse module supports essentially all of optparse’s features, and adds several additional ones, such as multiple arguments, better support for files, and more. Additionally, argparse’s handling of positional arguments is more consistent with its handling of options, and results in more robust handling as well as a more useful help output.

Правила использования необязательных аргументов командной строки.

Разберемся, как можно добавить необязательные параметры командной строки в файл prog.py:

# prog.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")

Запуск скрипта в командной строке даст вывод, представленный ниже.

$ python3 prog.py --verbosity 1
verbosity turned on
$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity
$ python3 prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument

Вот что здесь происходит:

  • Программа написана таким образом, чтобы что-то выводить, когда указан необязательный параметр --verbosity и ничего не выводить, если параметр не указан.
  • Опция является необязательной, т.к. при запуске программы без нее не будет ошибок.

    Обратите внимание

    , если необязательный параметр в командной строке не используется, то переменной, в данном случае args.verbosity, по умолчанию присваивается значение None. Это и является причиной того, что она не проходит проверку истинности в операторе if.

  • Справочное сообщение немного другое.

  • При использовании опции командной строки --verbosity необходимо также указать какое-то значение.

В приведенном выше примере для --verbosity, в командной строке, указывается произвольные целочисленное значение, но для этой программы на самом деле полезны только два значения: True или False.

Для этого изменим соответствующим образом код:

# prog.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

И вывод скрипта prog.py при запуске:

$ python3 prog.py --verbose
verbosity turned on
$ python3 prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python3 prog.py --help
usage: prog.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

Вот что здесь происходит:

  • Опция теперь больше похожа на флаг, чем на то, что требует значения. Мы изменили название опции на --verbose, чтобы соответствовать этой идее.

    Обратите внимание

    , что теперь указывается новое ключевое слово --verbose и присваиваем ему значение store_true. Это означает, что, если необязательный параметр указан, то модуль argparse присвоит args.verbose значение True. Отсутствие необязательного параметра --verbose в командной строке подразумевает args.verbose=False.

  • Скрипт prog.py будет ругаться, если указать значение параметру --verbose.

  • Обратите внимание на другой текст справки.

Короткие варианты необязательных параметров.

Если вы знакомы с использованием командной строки, то заметите, что еще не затронута тема коротких версий необязательных параметров.

Это довольно просто:

# prog.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

Вывод скрипта после его запуска. Обратите внимание, что новая возможность также отражена в тексте справки.

$ python3 prog.py -v
verbosity turned on
$ python3 prog.py --help
usage: prog.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

Introduction

Actually, this article is showing how to correct a syntax usage on using gunicorn. There is a requirement to start Django application using gunicorn. So, the following is an actual gunicorn service execution where it ends in a failure. The following is the status of the gunicorn service after failing on to start :

[root@localhost ~]# systemctl status gunicorn
● gunicorn.service - gunicorn daemon
Loaded: loaded (/usr/lib/systemd/system/gunicorn.service; disabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Thu 2021-11-18 02:43:05 UTC; 4s ago
Process: 8821 ExecStart=/home/django/env/bin/gunicorn --access-logfile --workers 3 --bind unix:/home/django/apps.sock apps.wsgi:application (code=exited, status=2)
Main PID: 8821 (code=exited, status=2)

Nov 18 02:43:05 localhost systemd[1]: Started gunicorn daemon.
Nov 18 02:43:05 localhost gunicorn[8821]: usage: gunicorn [OPTIONS] [APP_MODULE]
Nov 18 02:43:05 localhost gunicorn[8821]: gunicorn: error: argument --access-logfile: expected one argument
Nov 18 02:43:05 localhost systemd[1]: gunicorn.service: main process exited, code=exited, status=2/INVALIDARGUMENT
Nov 18 02:43:05 localhost systemd[1]: Unit gunicorn.service entered failed state.
Nov 18 02:43:05 localhost systemd[1]: gunicorn.service failed.
[root@localhost ~]#

Basically, there is a service script file for gunicorn to run the Django application. Before going on to the solution, the following is the actual content of the ‘gunicorn.service’ file :

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=django
Group=nginx
WorkingDirectory=/home/django/myapps
ExecStart=/home/django/env/bin/gunicorn --access-logfile --workers 3 --bind unix:/home/django/apps.sock apps.wsgi:application


[Install]
WantedBy=multi-user.target

Solution

Actually, the solution is very simple. It is only a matter of the gunicorn command pattern execution. In the gunicorn service script above, the following are the command execution of gunicorn :

/home/django/env/bin/gunicorn --access-logfile --workers 3 --bind unix:/home/django/apps.sock apps.wsgi:application

After executing it in the command line, it generates an error message. It is appear as in the gunicorn service status as follows :

gunicorn: error: argument --access-logfile: expected one argument

The solution is just by solving the gunicorn command pattern by revising the above command pattern as follows :

/home/django/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/django/apps.sock apps.wsgi:application

The point is in the following part :

--access-logfile --workers 3

into the following part :

--access-logfile - --workers 3

The new line will define the value of the parameter

--access-logfile

as

-

rather than not even define it as in the old line.

Purpose: Command line option and argument parsing.
Available In: 2.7 and later

The argparse module was added to Python 2.7 as a replacement
for optparse. The implementation of argparse supports
features that would not have been easy to add to optparse, and
that would have required backwards-incompatible API changes, so a new
module was brought into the library instead. optparse is still
supported, but is not likely to receive new features.

Comparing with optparse¶

The API for argparse is similar to the one provided by
optparse, and in many cases argparse can be used as a
straightforward replacement by updating the names of the classes and
methods used. There are a few places where direct compatibility could
not be preserved as new features were added, however.

You will have to decide whether to upgrade existing programs on a
case-by-case basis. If you have written extra code to work around
limitations of optparse, you may want to upgrade to reduce the
amount of code you need to maintain. New programs should probably use
argparse, if it is available on all deployment platforms.

Setting up a Parser¶

The first step when using argparse is to create a parser object
and tell it what arguments to expect. The parser can then be used to
process the command line arguments when your program runs.

The parser class is ArgumentParser. The constructor takes
several arguments to set up the description used in the help text for
the program and other global behaviors or settings.

import argparse
parser = argparse.ArgumentParser(description='This is a PyMOTW sample program')

Defining Arguments¶

argparse is a complete argument processing library. Arguments
can trigger different actions, specified by the action argument to
add_argument(). Supported actions include storing the argument
(singly, or as part of a list), storing a constant value when the
argument is encountered (including special handling for true/false
values for boolean switches), counting the number of times an argument
is seen, and calling a callback.

The default action is to store the argument value. In this case, if a
type is provided, the value is converted to that type before it is
stored. If the dest argument is provided, the value is saved to an
attribute of that name on the Namespace object returned when the
command line arguments are parsed.

Parsing a Command Line¶

Once all of the arguments are defined, you can parse the command line
by passing a sequence of argument strings to parse_args(). By
default, the arguments are taken from sys.argv[1:], but you can
also pass your own list. The options are processed using the GNU/POSIX
syntax, so option and argument values can be mixed in the sequence.

The return value from parse_args() is a Namespace
containing the arguments to the command. The object holds the argument
values as attributes, so if your argument dest is «myoption»,
you access the value as args.myoption.

Simple Examples¶

Here is a simple example with 3 different options: a boolean option
(-a), a simple string option (-b), and an integer option
(-c).

import argparse

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print parser.parse_args(['-a', '-bval', '-c', '3'])

There are a few ways to pass values to single character options. The
example above uses two different forms, -bval and -c val.

$ python argparse_short.py

Namespace(a=True, b='val', c=3)

The type of the value associated with ‘c’ in the output is an
integer, since the ArgumentParser was told to convert the
argument before storing it.

“Long” option names, with more than a single character in their name,
are handled in the same way.

import argparse

parser = argparse.ArgumentParser(description='Example with long option names')

parser.add_argument('--noarg', action="store_true", default=False)
parser.add_argument('--witharg', action="store", dest="witharg")
parser.add_argument('--witharg2', action="store", dest="witharg2", type=int)

print parser.parse_args([ '--noarg', '--witharg', 'val', '--witharg2=3' ])

And the results are similar:

$ python argparse_long.py

Namespace(noarg=True, witharg='val', witharg2=3)

One area in which argparse differs from optparse is the
treatment of non-optional argument values. While optparse
sticks to option parsing, argparse is a full command-line
argument parser tool, and handles non-optional arguments as well.

import argparse

parser = argparse.ArgumentParser(description='Example with non-optional arguments')

parser.add_argument('count', action="store", type=int)
parser.add_argument('units', action="store")

print parser.parse_args()

In this example, the “count” argument is an integer and the “units”
argument is saved as a string. If either is not provided on the
command line, or the value given cannot be converted to the right
type, an error is reported.

$ python argparse_arguments.py 3 inches

Namespace(count=3, units='inches')

$ python argparse_arguments.py some inches

usage: argparse_arguments.py [-h] count units
argparse_arguments.py: error: argument count: invalid int value: 'some'

$ python argparse_arguments.py

usage: argparse_arguments.py [-h] count units
argparse_arguments.py: error: too few arguments

Argument Actions¶

There are six built-in actions that can be triggered when an argument
is encountered:

store
Save the value, after optionally converting it to a different type.
This is the default action taken if none is specified expliclity.
store_const
Save a value defined as part of the argument specification, rather
than a value that comes from the arguments being parsed. This is
typically used to implement command line flags that aren’t booleans.
store_true / store_false
Save the appropriate boolean value. These actions are used to
implement boolean switches.
append
Save the value to a list. Multiple values are saved if the argument
is repeated.
append_const
Save a value defined in the argument specification to a list.
version
Prints version details about the program and then exits.
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', action='store', dest='simple_value',
                    help='Store a simple value')

parser.add_argument('-c', action='store_const', dest='constant_value',
                    const='value-to-store',
                    help='Store a constant value')

parser.add_argument('-t', action='store_true', default=False,
                    dest='boolean_switch',
                    help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,
                    dest='boolean_switch',
                    help='Set a switch to false')

parser.add_argument('-a', action='append', dest='collection',
                    default=[],
                    help='Add repeated values to a list',
                    )

parser.add_argument('-A', action='append_const', dest='const_collection',
                    const='value-1-to-append',
                    default=[],
                    help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',
                    const='value-2-to-append',
                    help='Add different values to list')

parser.add_argument('--version', action='version', version='%(prog)s 1.0')

results = parser.parse_args()
print 'simple_value     =', results.simple_value
print 'constant_value   =', results.constant_value
print 'boolean_switch   =', results.boolean_switch
print 'collection       =', results.collection
print 'const_collection =', results.const_collection
$ python argparse_action.py -h

usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f]
                          [-a COLLECTION] [-A] [-B] [--version]

optional arguments:
  -h, --help       show this help message and exit
  -s SIMPLE_VALUE  Store a simple value
  -c               Store a constant value
  -t               Set a switch to true
  -f               Set a switch to false
  -a COLLECTION    Add repeated values to a list
  -A               Add different values to list
  -B               Add different values to list
  --version        show program's version number and exit

$ python argparse_action.py -s value

simple_value     = value
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -c

simple_value     = None
constant_value   = value-to-store
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -t

simple_value     = None
constant_value   = None
boolean_switch   = True
collection       = []
const_collection = []

$ python argparse_action.py -f

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -a one -a two -a three

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = ['one', 'two', 'three']
const_collection = []

$ python argparse_action.py -B -A

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = ['value-2-to-append', 'value-1-to-append']

$ python argparse_action.py --version

argparse_action.py 1.0

Option Prefixes¶

The default syntax for options is based on the Unix convention of
signifying command line switches using a prefix of “-”.
argparse supports other prefixes, so you can make your program
conform to the local platform default (i.e., use “/” on Windows)
or follow a different convention.

import argparse

parser = argparse.ArgumentParser(description='Change the option prefix characters',
                                 prefix_chars='-+/',
                                 )

parser.add_argument('-a', action="store_false", default=None,
                    help='Turn A off',
                    )
parser.add_argument('+a', action="store_true", default=None,
                    help='Turn A on',
                    )
parser.add_argument('//noarg', '++noarg', action="store_true", default=False)

print parser.parse_args()

Set the prefix_chars parameter for the ArgumentParser to a
string containing all of the characters that should be allowed to
signify options. It is important to understand that although
prefix_chars establishes the allowed switch characters, the
individual argument definitions specify the syntax for a given switch.
This gives you explicit control over whether options using different
prefixes are aliases (such as might be the case for
platform-independent command line syntax) or alternatives (e.g., using
+” to indicate turning a switch on and “” to turn it off).
In the example above, +a and -a are separate arguments, and
//noarg can also be given as ++noarg, but not —noarg.

$ python argparse_prefix_chars.py -h

usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg]

Change the option prefix characters

optional arguments:
  -h, --help        show this help message and exit
  -a                Turn A off
  +a                Turn A on
  //noarg, ++noarg

$ python argparse_prefix_chars.py +a

Namespace(a=True, noarg=False)

$ python argparse_prefix_chars.py -a

Namespace(a=False, noarg=False)

$ python argparse_prefix_chars.py //noarg

Namespace(a=None, noarg=True)

$ python argparse_prefix_chars.py ++noarg

Namespace(a=None, noarg=True)

$ python argparse_prefix_chars.py --noarg

usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg]
argparse_prefix_chars.py: error: unrecognized arguments: --noarg

Sources of Arguments¶

In the examples so far, the list of arguments given to the parser have
come from a list passed in explicitly, or were taken implicitly from
sys.argv. Passing the list explicitly is useful
when you are using argparse to process command line-like
instructions that do not come from the command line (such as in a
configuration file).

import argparse
from ConfigParser import ConfigParser
import shlex

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

config = ConfigParser()
config.read('argparse_witH_shlex.ini')
config_value = config.get('cli', 'options')
print 'Config  :', config_value

argument_list = shlex.split(config_value)
print 'Arg List:', argument_list

print 'Results :', parser.parse_args(argument_list)

shlex makes it easy to split the string stored in the
configuration file.

$ python argparse_with_shlex.py

Config  : -a -b 2
Arg List: ['-a', '-b', '2']
Results : Namespace(a=True, b='2', c=None)

An alternative to processing the configuration file yourself is to
tell argparse how to recognize an argument that specifies an
input file containing a set of arguments to be processed using
fromfile_prefix_chars.

import argparse
from ConfigParser import ConfigParser
import shlex

parser = argparse.ArgumentParser(description='Short sample app',
                                 fromfile_prefix_chars='@',
                                 )

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print parser.parse_args(['@argparse_fromfile_prefix_chars.txt'])

This example stops when it finds an argument prefixed with @, then
reads the named file to find more arguments. For example, an input
file argparse_fromfile_prefix_chars.txt contains a series of
arguments, one per line:

The output produced when processing the file is:

$ python argparse_fromfile_prefix_chars.py

Namespace(a=True, b='2', c=None)

Automatically Generated Options¶

argparse will automatically add options to generate help and
show the version information for your application, if configured to do
so.

The add_help argument to ArgumentParser controls the
help-related options.

import argparse

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print parser.parse_args()

The help options (-h and —help) are added by default, but can
be disabled by setting add_help to false.

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print parser.parse_args()

Although -h and —help are defacto standard option names for
requesting help, some applications or uses of argparse either
don’t need to provide help or need to use those option names for other
purposes.

$ python argparse_with_help.py -h

usage: argparse_with_help.py [-h] [-a] [-b B] [-c C]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b B
  -c C

$ python argparse_without_help.py -h

usage: argparse_without_help.py [-a] [-b B] [-c C]
argparse_without_help.py: error: unrecognized arguments: -h

The version options (-v and —version) are added when
version is set in the ArgumentParser constructor.

import argparse

parser = argparse.ArgumentParser(version='1.0')

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print parser.parse_args()

print 'This is not printed'

Both forms of the option print the program’s version string, then
cause it to exit immediately.

$ python argparse_with_version.py -h

usage: argparse_with_version.py [-h] [-v] [-a] [-b B] [-c C]

optional arguments:
  -h, --help     show this help message and exit
  -v, --version  show program's version number and exit
  -a
  -b B
  -c C

$ python argparse_with_version.py -v

1.0

$ python argparse_with_version.py --version

1.0

Parser Organization¶

argparse includes several features for organizing your argument
parsers, to make implementation easier or to improve the usability of
the help output.

Sharing Parser Rules¶

It is common to need to implement a suite of command line programs
that all take a set of arguments, and then specialize in some way.
For example, if the programs all need to authenticate the user before
taking any real action, they would all need to support —user and
—password options. Rather than add the options explicitly to
every ArgumentParser, you can define a “parent” parser with
the shared options, and then have the parsers for the individual
programs inherit from its options.

The first step is to set up the parser with the shared argument
definitions. Since each subsequent user of the parent parser is going
to try to add the same help options, causing an exception, we turn off
automatic help generation in the base parser.

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('--user', action="store")
parser.add_argument('--password', action="store")

Next, create another parser with parents set:

import argparse
import argparse_parent_base

parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser])

parser.add_argument('--local-arg', action="store_true", default=False)

print parser.parse_args()

And the resulting program takes all three options:

$ python argparse_uses_parent.py -h

usage: argparse_uses_parent.py [-h] [--user USER] [--password PASSWORD]
                               [--local-arg]

optional arguments:
  -h, --help           show this help message and exit
  --user USER
  --password PASSWORD
  --local-arg

Conflicting Options¶

The previous example pointed out that adding two argument handlers to
a parser using the same argument name causes an exception. Change the
conflict resolution behavior by passing a conflict_handler. The two
built-in handlers are error (the default), and resolve, which
picks a handler based on the order they are added.

import argparse

parser = argparse.ArgumentParser(conflict_handler='resolve')

parser.add_argument('-a', action="store")
parser.add_argument('-b', action="store", help='Short alone')
parser.add_argument('--long-b', '-b', action="store", help='Long and short together')

print parser.parse_args(['-h'])

Since the last handler with a given argument name is used, in this
example the stand-alone option -b is masked by the alias for
—long-b.

$ python argparse_conflict_handler_resolve.py

usage: argparse_conflict_handler_resolve.py [-h] [-a A] [--long-b LONG_B]

optional arguments:
  -h, --help            show this help message and exit
  -a A
  --long-b LONG_B, -b LONG_B
                        Long and short together

Switching the order of the calls to add_argument() unmasks the
stand-alone option:

import argparse

parser = argparse.ArgumentParser(conflict_handler='resolve')

parser.add_argument('-a', action="store")
parser.add_argument('--long-b', '-b', action="store", help='Long and short together')
parser.add_argument('-b', action="store", help='Short alone')

print parser.parse_args(['-h'])

Now both options can be used together.

$ python argparse_conflict_handler_resolve2.py

usage: argparse_conflict_handler_resolve2.py [-h] [-a A] [--long-b LONG_B]
                                             [-b B]

optional arguments:
  -h, --help       show this help message and exit
  -a A
  --long-b LONG_B  Long and short together
  -b B             Short alone

Argument Groups¶

argparse combines the argument definitions into “groups.” By
default, it uses two groups, with one for options and another for
required position-based arguments.

import argparse

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('--optional', action="store_true", default=False)
parser.add_argument('positional', action="store")

print parser.parse_args()

The grouping is reflected in the separate “positional arguments” and
“optional arguments” section of the help output:

$ python argparse_default_grouping.py -h

usage: argparse_default_grouping.py [-h] [--optional] positional

Short sample app

positional arguments:
  positional

optional arguments:
  -h, --help  show this help message and exit
  --optional

You can adjust the grouping to make it more logical in the help, so
that related options or values are documented together. The
shared-option example from earlier could be written using custom
grouping so that the authentication options are shown together in the
help.

Create the “authentication” group with add_argument_group() and
then add each of the authentication-related options to the group,
instead of the base parser.

import argparse

parser = argparse.ArgumentParser(add_help=False)

group = parser.add_argument_group('authentication')

group.add_argument('--user', action="store")
group.add_argument('--password', action="store")

The program using the group-based parent lists it in the parents
value, just as before.

import argparse
import argparse_parent_with_group

parser = argparse.ArgumentParser(parents=[argparse_parent_with_group.parser])

parser.add_argument('--local-arg', action="store_true", default=False)

print parser.parse_args()

The help output now shows the authentication options together.

$ python argparse_uses_parent_with_group.py -h

usage: argparse_uses_parent_with_group.py [-h] [--user USER]
                                          [--password PASSWORD] [--local-arg]

optional arguments:
  -h, --help           show this help message and exit
  --local-arg

authentication:
  --user USER
  --password PASSWORD

Mutually Exclusive Options¶

Defining mutually exclusive options is a special case of the option
grouping feature, and uses add_mutually_exclusive_group()
instead of add_argument_group().

import argparse

parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument('-a', action='store_true')
group.add_argument('-b', action='store_true')

print parser.parse_args()

argparse enforces the mutal exclusivity for you, so that only
one of the options from the group can be given.

$ python argparse_mutually_exclusive.py -h

usage: argparse_mutually_exclusive.py [-h] [-a | -b]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b

$ python argparse_mutually_exclusive.py -a

Namespace(a=True, b=False)

$ python argparse_mutually_exclusive.py -b

Namespace(a=False, b=True)

$ python argparse_mutually_exclusive.py -a -b

usage: argparse_mutually_exclusive.py [-h] [-a | -b]
argparse_mutually_exclusive.py: error: argument -b: not allowed with argument -a

Nesting Parsers¶

The parent parser approach described above is one way to share options
between related commands. An alternate approach is to combine the
commands into a single program, and use subparsers to handle each
portion of the command line. The result works in the way svn,
hg, and other programs with multiple command line actions, or
sub-commands, does.

A program to work with directories on the filesystem might define
commands for creating, deleting, and listing the contents of a
directory like this:

import argparse

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help='commands')

# A list command
list_parser = subparsers.add_parser('list', help='List contents')
list_parser.add_argument('dirname', action='store', help='Directory to list')

# A create command
create_parser = subparsers.add_parser('create', help='Create a directory')
create_parser.add_argument('dirname', action='store', help='New directory to create')
create_parser.add_argument('--read-only', default=False, action='store_true',
                           help='Set permissions to prevent writing to the directory',
                           )

# A delete command
delete_parser = subparsers.add_parser('delete', help='Remove a directory')
delete_parser.add_argument('dirname', action='store', help='The directory to remove')
delete_parser.add_argument('--recursive', '-r', default=False, action='store_true',
                           help='Remove the contents of the directory, too',
                           )

print parser.parse_args()

The help output shows the named subparsers as “commands” that can be
specified on the command line as positional arguments.

$ python argparse_subparsers.py -h

usage: argparse_subparsers.py [-h] {list,create,delete} ...

positional arguments:
  {list,create,delete}  commands
    list                List contents
    create              Create a directory
    delete              Remove a directory

optional arguments:
  -h, --help            show this help message and exit

Each subparser also has its own help, describing the arguments and
options for that command.

$ python argparse_subparsers.py create -h

usage: argparse_subparsers.py create [-h] [--read-only] dirname

positional arguments:
  dirname      New directory to create

optional arguments:
  -h, --help   show this help message and exit
  --read-only  Set permissions to prevent writing to the directory

And when the arguments are parsed, the Namespace object
returned by parse_args() includes only the values related to the
command specified.

$ python argparse_subparsers.py delete -r foo

Namespace(dirname='foo', recursive=True)

Advanced Argument Processing¶

The examples so far have shown simple boolean flags, options with
string or numerical arguments, and positional arguments.
argparse supports sophisticated argument specification for
variable-length argument list, enumerations, and constant values as
well.

Variable Argument Lists¶

You can configure a single argument defintion to consume multiple
arguments on the command line being parsed. Set nargs to one of
these flag values, based on the number of required or expected
arguments:

Value Meaning
N The absolute number of arguments (e.g., 3).
? 0 or 1 arguments
* 0 or all arguments
+ All, and at least one, argument
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--three', nargs=3)
parser.add_argument('--optional', nargs='?')
parser.add_argument('--all', nargs='*', dest='all')
parser.add_argument('--one-or-more', nargs='+')

print parser.parse_args()

The parser enforces the argument count instructions, and generates an
accurate syntax diagram as part of the command help text.

$ python argparse_nargs.py -h

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                         [--optional [OPTIONAL]] [--all [ALL [ALL ...]]]
                         [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]

optional arguments:
  -h, --help            show this help message and exit
  --three THREE THREE THREE
  --optional [OPTIONAL]
  --all [ALL [ALL ...]]
  --one-or-more ONE_OR_MORE [ONE_OR_MORE ...]

$ python argparse_nargs.py

Namespace(all=None, one_or_more=None, optional=None, three=None)

$ python argparse_nargs.py --three

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                         [--optional [OPTIONAL]] [--all [ALL [ALL ...]]]
                         [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]
argparse_nargs.py: error: argument --three: expected 3 argument(s)

$ python argparse_nargs.py --three a b c

Namespace(all=None, one_or_more=None, optional=None, three=['a', 'b', 'c'])

$ python argparse_nargs.py --optional

Namespace(all=None, one_or_more=None, optional=None, three=None)

$ python argparse_nargs.py --optional with_value

Namespace(all=None, one_or_more=None, optional='with_value', three=None)

$ python argparse_nargs.py --all with multiple values

Namespace(all=['with', 'multiple', 'values'], one_or_more=None, optional=None, three=None)

$ python argparse_nargs.py --one-or-more with_value

Namespace(all=None, one_or_more=['with_value'], optional=None, three=None)

$ python argparse_nargs.py --one-or-more with multiple values

Namespace(all=None, one_or_more=['with', 'multiple', 'values'], optional=None, three=None)

$ python argparse_nargs.py --one-or-more

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                         [--optional [OPTIONAL]] [--all [ALL [ALL ...]]]
                         [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]
argparse_nargs.py: error: argument --one-or-more: expected at least one argument

Argument Types¶

argparse treats all argument values as strings, unless you tell
it to convert the string to another type. The type parameter to
add_argument() expects a converter function used by the
ArgumentParser to transform the argument value from a string
to some other type.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-i', type=int)
parser.add_argument('-f', type=float)
parser.add_argument('--file', type=file)

try:
    print parser.parse_args()
except IOError, msg:
    parser.error(str(msg))

Any callable that takes a single string argument can be passed as
type, including built-in types like int(), float(), and
file().

$ python argparse_type.py -i 1

Namespace(f=None, file=None, i=1)

$ python argparse_type.py -f 3.14

Namespace(f=3.14, file=None, i=None)

$ python argparse_type.py --file argparse_type.py

Namespace(f=None, file=<open file 'argparse_type.py', mode 'r' at 0x1004de270>, i=None)

If the type conversion fails, argparse raises an exception.
TypeError and ValueError exceptions are trapped automatically and
converted to a simple error message for the user. Other exceptions,
such as the IOError in the example below
where the input file does not exist, must be handled by the caller.

$ python argparse_type.py -i a

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: argument -i: invalid int value: 'a'

$ python argparse_type.py -f 3.14.15

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: argument -f: invalid float value: '3.14.15'

$ python argparse_type.py --file does_not_exist.txt

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: [Errno 2] No such file or directory: 'does_not_exist.txt'

To limit an input argument to a value within a pre-defined set, use
the choices parameter.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--mode', choices=('read-only', 'read-write'))

print parser.parse_args()

If the argument to —mode is not one of the allowed values, an
error is generated and processing stops.

$ python argparse_choices.py -h

usage: argparse_choices.py [-h] [--mode {read-only,read-write}]

optional arguments:
  -h, --help            show this help message and exit
  --mode {read-only,read-write}

$ python argparse_choices.py --mode read-only

Namespace(mode='read-only')

$ python argparse_choices.py --mode invalid

usage: argparse_choices.py [-h] [--mode {read-only,read-write}]
argparse_choices.py: error: argument --mode: invalid choice: 'invalid'
(choose from 'read-only', 'read-write')

File Arguments¶

Although file objects can instantiated with a single string
argument, that does not allow you to specify the access mode.
FileType gives you a more flexible way of specifying that an
argument should be a file, including the mode and buffer size.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-i', metavar='in-file', type=argparse.FileType('rt'))
parser.add_argument('-o', metavar='out-file', type=argparse.FileType('wt'))

try:
    results = parser.parse_args()
    print 'Input file:', results.i
    print 'Output file:', results.o
except IOError, msg:
    parser.error(str(msg))
    

The value associated with the argument name is the open file handle.
You are responsible for closing the file yourself when you are done
with it.

$ python argparse_FileType.py -h

usage: argparse_FileType.py [-h] [-i in-file] [-o out-file]

optional arguments:
  -h, --help   show this help message and exit
  -i in-file
  -o out-file

$ python argparse_FileType.py -i argparse_FileType.py -o temporary_file.
txt

Input file: <open file 'argparse_FileType.py', mode 'rt' at 0x1004de270>
Output file: <open file 'temporary_file.txt', mode 'wt' at 0x1004de300>

$ python argparse_FileType.py -i no_such_file.txt

usage: argparse_FileType.py [-h] [-i in-file] [-o out-file]
argparse_FileType.py: error: argument -i: can't open 'no_such_file.txt': [Errno 2] No such file or directory: 'no_such_file.txt'

Custom Actions¶

In addition to the built-in actions described earlier, you can define
custom actions by providing an object that implements the Action API.
The object passed to add_argument() as action should take
parameters describing the argument being defined (all of the same
arguments given to add_argument()) and return a callable object
that takes as parameters the parser processing the arguments, the
namespace holding the parse results, the value of the argument
being acted on, and the option_string that triggered the action.

A class Action is provided as a convenient starting point for
defining new actions. The constructor handles the argument
definitions, so you only need to override __call__() in the
subclass.

import argparse

class CustomAction(argparse.Action):
    def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None):
        argparse.Action.__init__(self,
                                 option_strings=option_strings,
                                 dest=dest,
                                 nargs=nargs,
                                 const=const,
                                 default=default,
                                 type=type,
                                 choices=choices,
                                 required=required,
                                 help=help,
                                 metavar=metavar,
                                 )
        print
        print 'Initializing CustomAction'
        for name,value in sorted(locals().items()):
            if name == 'self' or value is None:
                continue
            print '  %s = %r' % (name, value)
        return

    def __call__(self, parser, namespace, values, option_string=None):
        print
        print 'Processing CustomAction for "%s"' % self.dest
        print '  parser = %s' % id(parser)
        print '  values = %r' % values
        print '  option_string = %r' % option_string
        
        # Do some arbitrary processing of the input values
        if isinstance(values, list):
            values = [ v.upper() for v in values ]
        else:
            values = values.upper()
        # Save the results in the namespace using the destination
        # variable given to our constructor.
        setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser()

parser.add_argument('-a', action=CustomAction)
parser.add_argument('-m', nargs='*', action=CustomAction)
parser.add_argument('positional', action=CustomAction)

results = parser.parse_args(['-a', 'value', '-m' 'multi-value', 'positional-value'])
print
print results

The type of values depends on the value of nargs. If the argument
allows multiple values, values will be a list even if it only
contains one item.

The value of option_string also depends on the original argument
specifiation. For positional, required, arguments, option_string is
always None.

$ python argparse_custom_action.py


Initializing CustomAction
  dest = 'a'
  option_strings = ['-a']
  required = False

Initializing CustomAction
  dest = 'm'
  nargs = '*'
  option_strings = ['-m']
  required = False

Initializing CustomAction
  dest = 'positional'
  option_strings = []
  required = True

Processing CustomAction for "a"
  parser = 4299616464
  values = 'value'
  option_string = '-a'

Processing CustomAction for "m"
  parser = 4299616464
  values = ['multi-value']
  option_string = '-m'

Processing CustomAction for "positional"
  parser = 4299616464
  values = 'positional-value'
  option_string = None

Namespace(a='VALUE', m=['MULTI-VALUE'], positional='POSITIONAL-VALUE')

See also

argparse
The standard library documentation for this module.
original argparse
The PyPI page for the version of argparse from outside of the
standard libary. This version is compatible with older
versions of Python, and can be installed separately.
ConfigParser
Read and write configuration files.

При изучение питона решил изучить модуль optparse. В книге «Python в системном администрировании UNIX и Linux» этот модуль отлично описан, но в документаци сказанно, что развитие этого модуля будет продолжаться с argparse. Из-за этого я решил разобраться с этим модулем.

Далее попробую кратко разобрать модуль argparse.

Для примера был написан скрипт, который удаляет папки, дата которых больше определённого количества дней. Например, есть папка «2012-05-5», которая, при стандартном вызове скрипта, удалится через 7 дней от даты в имени.
Сам скрипт:

		#!/usr/bin/python
		#! -*- coding: utf-8 -*-
		import subprocess,datetime,os,argparse
		import proverka #модуль проверки на удаление


		def main():
		    m = argparse.ArgumentParser(description="Удаление папок с помощью %(prog)s", 
		                                               epilog="Эпилог программы %(prog)s",prog="del_f")
											
		    m.add_argument("--day","-d",type=int, default=7, 
		                        help="Количество дней, прошедших с даты в названии папки(для удаления)")
				
		    m.add_argument("--dir","-p",type=str,default='.', help="Путь к удаляемым папкам")
		    m.add_argument("--verbose","-v",action="store_true", 
		                        help="Выводить подробное описание действий",default=False)
		    m.add_argument("--exception","-e",type=str, default="",action="store",nargs='+', 
		                                         help="Исключить папки")
		    options = m.parse_args()
		    p=subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE)
		    out = p.stdout.read()
		    mas_p=out.split('n')
		    options =  vars(options)
		    options['dir'] += '/'
		    ex = options['exception']
		    print options['exception']

		    for t in mas_p:
		        if t not in ex:
			    if (proverka.proverka(t,options['day'])[0] == 'True'):
			        dell = 'rm -rf ' + options['dir'] + proverka.proverka(t,options['day'])[1]
				if options['verbose']:
				    print "Folder '" + proverka.proverka(t,options['day'])[1]  + "' is Deleting"
				subprocess.call(dell,shell=True)

		if __name__ == '__main__':
		    main()
		
Создание класса argparse.ArgumentParser.

Для начала рассмотрим работу класса argparse.ArgumentParser, который имеет вид:

class argparse.ArgumentParser([description][, epilog][, prog][, usage][, add_help][, argument_default][, parents][, prefix_chars][, conflict_handler][, formatter_class])
Аргумент description производит краткое описание того, что делает программа.
Результат отображается перед дополнительными аргументами.
Аналогично description работает epilog, но результат выводится после дополнительных аргументов:

rroot@kanst9:> python py.py -h
			usage: ...
			Удаление папок
			optional arguments:
			  ...
			Эпилог

Рассмотрим 2 варианта работы программы с аргументом prog:

m = argparse.ArgumentParser(description="Удаление папок с помощью %(prog)s",
						epilog="Эпилог программы %(prog)s")

Результат 1:

root@kanst9:> python py.py -h
			usage: ...
			Удаление папок с помощью df.py
			optional arguments:
			 ...
			Эпилог программы df.py

Для вставки мы использовали конструкцию %(prog)s. По умолчанию используется sys.argv[0].Теперь установим значение prog=«del_f»

m = argparse.ArgumentParser(description="Удаление папок с помощью %(prog)s",
						epilog="Эпилог программы %(prog)s" ,prog="del_f")

Результат 2:

root@kanst9:> python py.py -h
			usage: ....
			Удаление папок с помощью del_f
			optional arguments:
			  ...
			Эпилог программы del_f

С помощью аргумента prog можно задать название программы, и использовать это в справке.

Для краткого описания работы можно использовать аргумент usage
Пример:

m = argparse.ArgumentParser(..., usage='%(prog)s [arguments]')

Результат:

root@kanst9:> python py.py -h
			usage: del_f [arguments]

По умолчанию usage выглядит так:

usage: %(prog)s [аргументы]

Описание остальных аргументов можно посмотреть тут.

Добавление аргументов.

После создания парсера можно перейти к добавлению аргументов
Метод добавления аргументов выглядит следующим образом:

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type]
				[, choices][, required][, help][, metavar][, dest])

action=«store» — хранит значение аргумента.
action=«store_const» -хранит значение, указанное к *const*

parser.add_argument('--foo', action='store_const', const=2)

action=«store_true[false]» — аналогично store_const*, но хранит значения True и False.
version — добавляет аргумент версии.

parser.add_argument('--version', action='version', version='%(prog)s 2.0')

Добавим аргумент числа дней:

m.add_argument("--day","-d",type=int, default=7, help="Количество дней, прошедших с даты в названии папки(для удаления)")

Здесь:
type=int — указывает на формат данных.
default=7 -значение по умолчанию, равное 7.
help=»…» — описание аргумента, отображаемое в помощи.
Добавим аргумент пути:

m.add_argument("--dir","-p",type=str,default='.', help="Путь к удаляемым папкам")

Здесь всё как и в предыдущем аргументе.

Для подробного вывода работы скрипта создаётся аргумент:

m.add_argument("--verbose","-v",action="store_true", help="Выводить подробное описание действий", default=False)

action=«store_true» — показывает, что значение аргумента принимает только 2 значения True и False(по умолчанию)

Аргумент

m.add_argument("--exception","-e",type=str, default="", nargs='+', help="Исключить папки")

Исключает папки из удаляемых.
nargs=’+’ — заносит данные в список, причем если отсутствует хотя бы 1 аргумент, создаётся сообщение об ошибке.
При использовании nargs=’*’ сообщения об ошибке не будет.

root@kanst9:> python py.py -e
			usage: del_f [-h] [--day DAY] [--dir DIR] [--verbose]
				             [--exception EXCEPTION [EXCEPTION ...]]
			del_f: error: argument --exception/-e: expected at least one argument
Работа с аргументами.

С помощью метода parse_args() можно вывести аргументы:

print m.parse.args()
			Namespace(day=7, dir='.', exception='', verbose=False)

А с помощью vars(m.parse.args()) можно преобразовать результат в словарь:

print vars(m.parse.args())
			{'exception': '', 'day': 7, 'dir': '.', 'verbose': False}
Примеры работы скрипта:

root@kanst9:> ls
				2012-05-10/  2012-05-17/  2012-05-5/  df.py
				2012-05-13/  2012-05-4/   2012-05-9/  proverka.py
				root@kanst9:> python df.py -h    
				usage: del_f [-h] [--day DAY] [--dir DIR] [--verbose]
				             [--exception EXCEPTION [EXCEPTION ...]]

				Удаление папок с помощью del_f

				optional arguments:
				  -h, --help            show this help message and exit
				  --day DAY, -d DAY     Количество дней, прошедших с
				                        даты в названии папки(для
				                        удаления)
				  --dir DIR, -p DIR     Путь к удаляемым папкам
				  --verbose, -v         Выводить подробное описание
				                        действий
				  --exception EXCEPTION [EXCEPTION ...], -e EXCEPTION [EXCEPTION ...]
				                        Исключить папки

				Эпилог программы del_f

				root@kanst9:> python df.py -v  

				Folder  '2012-05-10'  is Deleting
				Folder  '2012-05-4'  is Deleting
				Folder  '2012-05-5'  is Deleting
				Folder  '2012-05-9'  is Deleting
				root@kanst9:> ls
				2012-05-10/  2012-05-17/  2012-05-5/  df.py
				2012-05-13/  2012-05-4/   2012-05-9/  proverka.py
				root@kanst9:> python df.py -v -d 10

				Folder  '2012-05-4'  is Deleting
				Folder  '2012-05-5'  is Deleting

				root@kanst9:> ls
				2012-05-10/  2012-05-17/  2012-05-5/  df.py
				2012-05-13/  2012-05-4/   2012-05-9/  proverka.py

				root@kanst9:> python df.py -v -d 10 -e 2012-05-4

				Folder  '2012-05-5'  is Deleting

P.S. Статью пишу первый раз. Хотелось бы услышать критику и пожелания.

Понравилась статья? Поделить с друзьями:
  • Error archive structure corrupted descriptor failed crc check
  • Error archive structure corrupted decompression of control block failed
  • Error archive data corrupted decompression fails что делать
  • Error bad ref for git logs head
  • Error bad pathname