Link to home
Start Free TrialLog in
Avatar of beer9
beer9Flag for India

asked on

How to add a variable in method's argument in python?

Below code works perfectly now I want to provide ObjectType(ObjectIdentity()) as a variable which will be constructed as a list of OID

from pysnmp.hlapi import *

g = getCmd(SnmpEngine(),
           CommunityData('myPa$$word'),
           UdpTransportTarget(('loadbalancer-staging.com', 161)),
           ContextData(),
           ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
		   ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')))

for x in next(g)[3]:
    print x

Open in new window

I have a list of OID as below and somehow I want to put that in getCmd method as a variable
mibs = ['1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.6.0']

Open in new window

so basically I have a dynamic list of OID (minimum 3 and maximum 9 ) and I want to supple them as a variable in above code so that in ONE SNMP call I will get output of all the OIDs. Is there a way I can do it? Thanks!
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of beer9

ASKER

Thanks @gelonida it helps,

I am new to python and curios to know what is happening here?

*object_types

Open in new window


what is the role of * here?
In the python world the star before a list variable or before a list ist often referenced as *args.
two stars before a dict variable are often referenced as kwargs.

You can read following article about it. https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

If you have a list (e.g. the variable l) with n  elements, then wherever you use a *l in a function call, *l will be used as the next n parameters of that function call.

Example:

>>> def f(a,b,c,d,e):
...      print("a = %s b=%s c=%s d=%s e=%s" % (a,b,c,d,e))
... 
>>> f(1,2,3,4,5)
a = 1 b=2 c=3 d=4 e=5
>>> l=['a', 'b', 'c', 'd', 'e']
>>> f(*l)
a = a b=b c=c d=d e=e
>>> l=['a','b']
>>> f(1,2,3,*l)
a = 1 b=2 c=3 d=a e=b

Open in new window


You have also the reverse construct, where *args is being used in a function declaration.
This allows to create a function with a variable amount of parameters.

example:

>>> def f(a,b, *args):
...     print("a=%s b=%s other args are %s" % (a,b, args))
... 
>>> f(1,2)
a=1 b=2 other args are ()
>>> f(1,2,3)
a=1 b=2 other args are (3,)
>>> f(1,2,3,4)
a=1 b=2 other args are (3, 4)
>>> 

Open in new window