Python Forum
Use a block of code only one time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use a block of code only one time
#1
Hi All,

I have a below piece of code, Is it possible to use the green color code single time for different variables ?
Right now this code run as:
#python3.6 testing.py -i desert -w 380 -c 400
OK - Active Users: 368
OR
#python3.6 testing.py -i ocean -w 380 -c 400
OK - Active Users: 65

*Note Please assume that i am parsing command line arguments. And variable tuple stored different numbers

# validate args
if len(sys.argv)==1:
    print("# Usage:\t -w <warn> -c <crit>")
    sys.exit("No argument pass") 
elif input_value == "desert": 
    if tuple[0] > c_value: 
        print("CRITICAL - Active: ",tuple[0])
        sys.exit(2)
    elif tuple[0] > w_value: 
        print("WARNING - Active:",tuple[0])
        sys.exit(1)
    else:
        print("OK - Active Users:",tuple[0])
        sys.exit(0)
elif input_value == "ocean":
    ###Again use the above chunk of code in green which check critical, warning and ok condition just change to tuple[1] > c_value and so on###
Regards,
rlinux57
Reply
#2
This is exactly the purpose of a function().
Here I pass the index (idx) for test_tuple() but you can make a for and check all the content of t too.

def test_tuple(input_value, t, idx):
	if input_value in ["desert", "ocean"]: 
		if t[0] > c_value: 
			print("CRITICAL - Active: ",t[idx])
			sys.exit(2)
		elif t[0] > w_value: 
			print("WARNING - Active:",t[idx])
			sys.exit(1)
		else:
			print("OK - Active Users:",t[idx])
			sys.exit(0)
	else:
		print("Invalid input")


# 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, idx)
PS: If you use tuple in your code, you'll overwrite the tuple class of python!
Reply
#3
Hi again,

Got below error, How do i define idx ?
Error:
"message": "E0602:Undefined variable 'idx'"
Now code looks:
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)
     

# parse command line args 
def test_tuple(input_value, t, idx):
    if input_value in ["desert", "ocean"]: 
        if t[0] > c_value: 
            print("CRITICAL - Active: ",t[idx])
            sys.exit(2)
        elif t[0] > w_value: 
            print("WARNING - Active:",t[idx])
            sys.exit(1)
        else:
            print("OK - Active Users:",t[idx])
            sys.exit(0)
    else:
        print("Invalid input")
 
 
# 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, idx)
Regards,
rlinux57
Reply
#4
idx is the index of the tuple t.
You have to define its value before calling test_tuple():

For the first position...
# validate args
if len(sys.argv)==1:
    print("# Usage:\t -w <warn> -c <crit>")
    sys.exit("No argument pass") 
else:
    idx = 0
    test_tuple(input_value, t, idx)
Reply
#5
Hi again,

The output of argument desert is fine, But when i mentioned ocean it shows the output of desert again.

Output:
#python3.6 script.py -i desert -w 10 -c 20 CRITICAL - Active: 205 #python3.6 script.py -i ocean -w 10 -c 20 CRITICAL - Active: 205
Regards,
rlinux57
Reply
#6
Could you post your entire code?
Reply
#7
(Sep-18-2018, 07:22 PM)rlinux57 Wrote: The output of argument desert is fine, But when i mentioned ocean it shows the output of desert again.

There is no output of desert that is different than the output of ocean. The condition of line 12 is for both. If t and idx are determined by the other arguments, then the output is going to be the same if the only argument you change is desert vs. ocean.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
Hi,

Below is the code, Please look into it.

if __name__ == "__main__": 
    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)

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

# validate args
if len(sys.argv)==1:
    print("# Usage:\t -w <warn> -c <crit>")
    sys.exit("No argument pass") 
else:
    idx = 0
    test_tuple(input_value, t, idx)
Reply
#9
I agree with @ichabod801...with same input it will result in same output.

Your code and idea are a little bit confusing.
In your OP, what is the expected value of tuple?
Reply
#10
Hi again,

Lets suppose tuple variable stores values, It could be store more values:

tuple = (786 , 200)

When the argument value is equal to desert then it checks warning, critical and ok level then show value:

Output:
OK - Active: 786
#Value could be critical or warning depends on -w and -c arguments we set.


OR when chooses ocean

Output:
OK - Active: 200
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python multiple try except block in my code -- can we shorten code mg24 10 6,143 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  "If Len(Word) == 0" Code Block in Pig Latin Program new_coder_231013 3 2,066 Jan-02-2022, 06:03 PM
Last Post: deanhystad
  Try,Except,Else to check that user has entered either y or n (Code block pasted) RandomNameGenerator 3 2,337 Jun-29-2021, 08:21 PM
Last Post: RandomNameGenerator
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,253 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Stumped by my own code (ratio & epoch-time calculation). MvGulik 2 2,140 Dec-30-2020, 12:04 AM
Last Post: MvGulik
  Code taking too much time to process ErPipex 11 4,958 Nov-16-2020, 09:42 AM
Last Post: DeaD_EyE
  What is the run time complexity of this code and please explain? samlee916 2 2,300 Nov-06-2020, 02:37 PM
Last Post: deanhystad
  The count variable is giving me a hard time in this code D4isyy 2 1,974 Aug-09-2020, 10:32 PM
Last Post: bowlofred
  Having a hard time combining two parts of code. Coozeki 6 3,091 May-10-2020, 06:50 AM
Last Post: Coozeki
  Block of code, scope of variables and surprising exception arbiel 8 3,427 Apr-06-2020, 07:57 PM
Last Post: arbiel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020