Python Forum
Use a block of code only one time - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Use a block of code only one time (/thread-12903.html)

Pages: 1 2


RE: Use a block of code only one time - gontajones - Sep-20-2018

import getopt
import sys


# parse command line args
def test_tuple(input_value, t):
    possible_opts = ["desert", "ocean"]
    if input_value in possible_opts:
        if t[possible_opts.index(input_value)] > c_value:
            print("CRITICAL - Active: ", t[possible_opts.index(input_value)])
            sys.exit(2)
        elif t[possible_opts.index(input_value)] > w_value:
            print("WARNING - Active:", t[possible_opts.index(input_value)])
            sys.exit(1)
        else:
            print("OK - Active:", t[possible_opts.index(input_value)])
            sys.exit(0)
    else:
        print("Invalid input")


if __name__ == "__main__":

    t = (786, 200)

    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:w:c:")
    except getopt.GetoptError:
        print("Usage: v2.py -i name -w 10 -c 20")
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-i':
            input_value = arg
        elif opt == '-w':
            w_value = int(arg)
        elif opt == '-c':
            c_value = int(arg)

    # validate args
    if len(sys.argv) == 1:
        print("# Usage:\t -w <warn> -c <crit>")
        sys.exit("No argument pass")
    else:
        test_tuple(input_value, t)
But I suggest you use a dictionary, like:
possible_opts = {
        "desert": 786,
        "ocean": 200
}



RE: Use a block of code only one time - ichabod801 - Sep-20-2018

Then you need to make sure idx is set differently for ocean and desert. From your original post it seems you are not setting idx at all. So you need to set that using a conditional based on input_value.

if input_vale == 'desert':
    idx = 0
else:
    idx = 1



RE: Use a block of code only one time - rlinux57 - Sep-20-2018

Hi gontajones,

Now it's working. Could you please explain the condition possible_opts.index(input_value)] . I didn't understand the index.

Regards,
rlinux57


RE: Use a block of code only one time - gontajones - Sep-20-2018

Check this link Data Structures
>>> t = [0,1,2,3,4]
>>> possible_opts = ["a","b","c","d","e"]
>>> t
[0, 1, 2, 3, 4]
>>> possible_opts
['a', 'b', 'c', 'd', 'e']
>>> possible_opts.index("a")
0
>>> possible_opts.index("c")
2
>>> t[0]
0
>>> t[2]
2
>>> t[possible_opts.index("a")]
0
>>> t[possible_opts.index("c")]
2
>>>



RE: Use a block of code only one time - rlinux57 - Sep-21-2018

Hi gontajones,

Thank you for helping me.

Regards,
rlinux57