Jak odczytać / przetworzyć argumenty wiersza poleceń?

Author: martineau, 2009-06-18

17 answers

Kanonicznym rozwiązaniem w bibliotece standardowej jest argparse (docs):

Oto przykład:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse podpory (między innymi):

  • Wiele opcji w dowolnej kolejności.
  • opcje krótkie i długie.
  • wartości domyślne.
  • generowanie komunikatu pomocy dotyczącej użycia.
 307
Author: Ayman Hourieh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-23 21:33:25
import sys

print("\n".join(sys.argv))

sys.argv jest listą zawierającą wszystkie argumenty przekazane do skryptu w wierszu poleceń.

Zasadniczo,

import sys
print(sys.argv[1:])
 447
Author: John Slavick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-07 12:32:54

Po prostu chodzenie ewangelizując dla argparse co jest lepsze dlatych powodów.. zasadniczo:

(skopiowane z linku)

  • Moduł Argparse może obsługiwać pozycjonowanie oraz opcjonalne argumenty, podczas gdy optparse może obsługiwać tylko opcjonalnie argumenty

  • Argparse nie jest dogmatyczny jaki jest Twój interfejs wiersza poleceń powinno wyglądać jak-options jak-file or / file are supported, as are wymagane opcje. Optparse odmawia na obsługują te funkcje, preferując czystość nad praktycznością

  • Argparse produkuje więcej informacje o użytkowaniu, w tym użycie wiersza poleceń określone z twoje argumenty i wiadomości pomocy dla zarówno pozycyjny jak i opcjonalny argumenty. Moduł optparse wymaga napisania własnego użycia ciągiem, i nie ma możliwości wyświetlenia pomoc w pozycjonowaniu.

  • Argparse wspiera działania, które zużywaj zmienną liczbę args linii poleceń, natomiast optparse wymaga dokładnej liczby argumenty (np. 1, 2 lub 3) są znane z góry

  • Argparse obsługuje parsery, które wysyłanie do Pod-komend, podczas gdy optparse wymaga ustawienia allow_interspersed_args i robiąc Parser dispatch manually

I moje ulubione:

  • argparse pozwala na typ i parametry działania do add_argument() do określenia za pomocą prostego callables, natomiast optparse wymaga hakowanie atrybutów klas jak STORE_ACTIONS lub CHECK_METHODS aby uzyskać właściwe sprawdzanie argumentów
 122
Author: Silfheed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-26 18:15:02

Istnieje również argparse moduł stdlib ("impovement" na module stdlib optparse). Przykład z wstęp do argparse :

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Użycie:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10
 62
Author: jfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-10 19:30:02

Jednym ze sposobów jest użycie sys.argv. To wyświetli nazwę skryptu jako pierwszy argument i wszystkie inne parametry, które do niego przekazujesz.

import sys

for arg in sys.argv:
    print arg
 45
Author: JPCosta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-09 20:46:58

Biblioteka docopt jest naprawdę śliska. Buduje argument dict z ciągu użycia dla Twojej aplikacji.

Np z docopt readme:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)
 38
Author: ralbatross,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-09 16:52:31

Jeśli potrzebujesz czegoś szybkiego i niezbyt elastycznego

Main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

Następnie uruchom python main.py James Smith

Aby wytworzyć następujące Wyjście:

Hello James Smith

 26
Author: Kent Munthe Caspersen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-29 09:38:42
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
 22
Author: whi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-13 23:50:32

Sam używam optparse, ale bardzo podoba mi się kierunek, w którym podąża Simon Willison ze swoją niedawno wprowadzoną biblioteką optfunc. Działa przez:

"introspekcja funkcji definicja (wraz z jej argumentami i ich wartości domyślnych) oraz za pomocą że do zbudowania wiersza poleceń parser argumentów."

Więc, na przykład, ta definicja funkcji:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

Jest zamieniany na tekst pomocy optparse:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER
 17
Author: Van Gale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-18 04:07:57

Lubię getopt z stdlib, np:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Ostatnio owijałem coś podobnego do tego, aby uczynić rzeczy mniej gadatliwymi(np. czyniąc" - h " dorozumianym).

 7
Author: Peter Ericson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-18 01:30:28

Jak widać optparse "moduł optparse jest przestarzały i nie będzie dalej rozwijany; rozwój będzie kontynuowany za pomocą modułu argparse."

 7
Author: tverrbjelke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-23 12:57:14

Pocoo ' s click jest bardziej intuicyjny, wymaga mniej boilerplate i jest co najmniej tak samo potężny jak argparse.

Jedyną słabością, z jaką do tej pory się spotkałem, jest to, że nie można zbytnio dostosowywać stron pomocy, ale zazwyczaj nie jest to wymóg i docopt wydaje się oczywistym wyborem, gdy jest.

 6
Author: Ryne Everett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-12 19:38:40

Być może zainteresuje cię mały moduł Pythona, który napisałem, aby jeszcze łatwiej obsługiwać argumenty linii poleceń (open source i free To use) - Commando

 4
Author: Mufasa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-06 19:28:43

Polecam spojrzeć na docopt jako prostą alternatywę dla tych innych.

Docopt jest nowym projektem, który działa poprzez parsowanie komunikatu --help, a nie wymaganie od Ciebie samodzielnej implementacji. Musisz tylko umieścić wiadomość użycia w formacie POSIX.

 4
Author: David C. Bishop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-18 06:21:51

Jeszcze jedną opcją jest argh . Opiera się na argparse i pozwala pisać takie rzeczy jak:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()

Automatycznie wygeneruje pomoc i tak dalej, a Ty możesz użyć dekoratorów, aby dostarczyć dodatkowych wskazówek, jak powinno działać parsowanie arg.

 3
Author: circular-ruin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-11 22:10:35
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h

Ref-link: https://docs.python.org/3.3/library/argparse.html
 1
Author: JON,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-07 03:25:07

Moim rozwiązaniem jest entrypoint2 . Przykład:

from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True): 
    ''' This function writes report.

    :param file: write report to FILE
    :param quiet: don't print status messages to stdout
    '''
    print file,quiet

Tekst pomocy:

usage: report.py [-h] [-q] [--debug] file

This function writes report.

positional arguments:
  file         write report to FILE

optional arguments:
  -h, --help   show this help message and exit
  -q, --quiet  don't print status messages to stdout
  --debug      set logging level to DEBUG
 0
Author: ponty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-24 12:48:37