optparse und Argumente...

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Benutzeravatar
jens
Python-Forum Veteran
Beiträge: 8502
Registriert: Dienstag 10. August 2004, 09:40
Wohnort: duisburg
Kontaktdaten:

Ich brech mir gerad einen ab :cry:

Ich hab ein Programm welches nur ein Aktions-Argument benötigt... Meine bisherige Lösung:

Code: Alles auswählen

#!/usr/bin/python
# -*- coding: ISO-8859-1 -*-

"""
    install     - Install PyAdmin as inetd services
    deinstall   - DeInstall PyAdmin (inetd services)
    start       - Start stand alone PyAdmin server
    stop        - Stops a runing stand alone PyAdmin server
"""

import optparse


OptParser = optparse.OptionParser( usage = __doc__ )

options, args = OptParser.parse_args()

if len(args) != 1:
    OptParser.error("wrong argument!")

action = args[0]

if action == "install":
    install()
elif action == "deinstall":
    deinstall()
elif action == "start":
    start_server()
elif action == "stop":
    stop_server()

OptParser.error("wrong argument!")
So optimal ist das aber nicht, was?

GitHub | Open HUB | Xing | Linked in
Bitcoins to: 1JEgSQepxGjdprNedC9tXQWLpS424AL8cd
Leonidas
Python-Forum Veteran
Beiträge: 16025
Registriert: Freitag 20. Juni 2003, 16:30
Kontaktdaten:

jens hat geschrieben:So optimal ist das aber nicht, was?
Also ich finde meine Lösung eleganter (etwas gekürzt):

Code: Alles auswählen

#!/usr/bin/python
# -*- coding: ISO-8859-1 -*-
import optparse

OptParser = optparse.OptionParser()
options, args = OptParser.parse_args()

if len(args) != 1:
    OptParser.error("wrong argument!")

# funktionen schnell mal erstellen
install, deinstall, start_server, stop_server = [lambda: 1+1] * 4
    
funcs = {"install" : install, "deinstall" : deinstall, 
    "start" : start_server, "stop" : stop_server}

argfound = False
for mode in funcs.keys():
    if mode in args:
        argfound = True
        print funcs[mode]()

if not argfound:
    OptParser.error("wrong argument!")
My god, it's full of CARs! | Leonidasvoice vs (former) Modvoice
BlackJack

Die erste Fehlermeldung sollte nicht "wrong argument" sein, weil kein Argument übergeben wurde, welches falsch sein könnte. :wink:

Wenn Du wirklich keine Optionen brauchst, sondern nur Argumente, dann würde ich 'optparse' weglassen und gleich 'sys.argv' benutzen. Ich hätt's wohl so geschrieben:

Code: Alles auswählen

#!/usr/bin/env python
import sys

install, deinstall, start_server, stop_server = [lambda: None] * 4

functions = { 'install': install, 'deinstall': deinstall,
              'start': start_server, 'stop': stop_server }

if len(sys.argv) < 2:
    print 'Usage ....'
    sys.exit(1)

argument = sys.argv[1]

try:
    functions[argument]()
except KeyError:
    print 'Unknown argument %r' % argument
    sys.exit(2)
Antworten