Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - sys.argv and flag identification

when I accept arguments how do I check if two show up at the same time without having a compound conditional

i.e.

#!/usr/bin/python
import random, string
import mymodule
import sys

z = ' '.join(sys.argv[2:])
q = ''.join(sys.argv[3:])
a = ''.join(sys.argv[2:])
s = ' '.join(sys.argv[1:])
flags = sys.argv[1:5]

commands = [["-r", "reverse string passed next with no quotes needed."], ["-j", "joins arguments passed into string. no quotes needed."], ["--palindrome", "tests whether arguments passed are palindrome or not. collective."],["--rand","passes random string of 10 digits/letters"]]

try:
    if "-r" in flags:
        if "-j" in flags:
            print mymodule.reverse(q)
        if not "-j" in flags:
            print mymodule.reverse(z)

    if "-j" in flags:
        if not "-r" in flags:
            print a

    if "--palindrome" in flags: mymodule.ispalindrome(z)

    if (not "-r" or not "-j" or not "--palindrome") in flags: mymodule.say(s)

    if "--rand" in flags: print(''.join([random.choice(string.ascii_letters+"123456789") for f in range(10)]))

    if not sys.argv[1]: print mymodule.no_arg_error

    if "--help" in flags: print commands

except: print mymodule.no_arg_error

i just want to be able to say

if "-r" and "-j" in flags in no particular order: do whatever

like image 614
tekknolagi Avatar asked Jan 09 '11 22:01

tekknolagi


People also ask

What is SYS argv in Python?

sys. argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments.

What does Sys argv 1 do in Python?

sys. argv[1] contains the first command line argument passed to your script.

What Python object type is sys argv?

argv comes handy. The sys. argv is a list object which is available in the Python's sys module. It stores all the command-line arguments passed to a Python script as string objects. The arguments that we pass from the command line are stored as strings in the sys.


1 Answers

Something like

import optparse

p = optparse.OptionParser()
p.add_option('--foo', '-f', default="yadda")
p.add_option('--bar', '-b')
options, arguments = p.parse_args()

# if options.foo and options.bar ...
like image 141
Bjorn Avatar answered Sep 29 '22 07:09

Bjorn