Daniel F
Daniel F

Reputation: 14239

Call a Python function containing an asterisk with a name in the parameters

In the python module pysnmp there is a function named cmdGen.nextCmd with the following definition

nextCmd(authData,
        transportTarget,
        *varNames, # <------- point of interest
        lookupNames=False,
        lookupValues=False,
        lexicographicMode=False,
        ignoreNonIncreasingOid=False,
        maxRows=0)

I can call this function this way:

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
  cmdgen.CommunityData('public'),
  cmdgen.UdpTransportTarget(('192.168.0.1', 161)),
  '1.3.6.1.4.1.14988.1.1.1.2.1.3', # strength
  '1.3.6.1.4.1.14988.1.1.1.2.1.4', # tx-bytes
  '1.3.6.1.4.1.14988.1.1.1.2.1.5', # rx-bytes
  lookupValues=False
)

apparently the oid's (strength, tx-bytes, rx-bytes) are passed to the nextCmd function via the *varNames parameter.

I'm trying to archive something along these lines:

oids = (                           # dynamically generated
  '1.3.6.1.4.1.14988.1.1.1.2.1.3', # strength
  '1.3.6.1.4.1.14988.1.1.1.2.1.4', # tx-bytes
  '1.3.6.1.4.1.14988.1.1.1.2.1.5'  # rx-bytes
)

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
  cmdgen.CommunityData('public'),
  cmdgen.UdpTransportTarget(('192.168.0.1', 161)),
  oids, # these are the oid's
  lookupValues=False
)

but it does yield a

AttributeError: 'tuple' object has no attribute 'split'

How can bundle the oid's into a variable and pass them to the nextCmd? I'm extracting the oid's from a dict, so I don't want to hard-code them.

Upvotes: 1

Views: 98

Answers (2)

d6bels
d6bels

Reputation: 1482

This is like an argument list so you just need to put a * in front of oids to get it working.

This will unpack the tuple just as if you had given each oid as a plain argument.

Your code :

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
  cmdgen.CommunityData('public'),
  cmdgen.UdpTransportTarget(('192.168.0.1', 161)),
  *oids, # these are the oid's
  lookupValues=False
)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121904

You need to use the *args syntax in the call here:

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
  cmdgen.CommunityData('public'),
  cmdgen.UdpTransportTarget(('192.168.0.1', 161)),
  *oids,
  lookupValues=False
)

This passes in each value in oids as a separate argument.

Note that this is a different but deliberately similar concept to using *args in a function signature. In a call, it expands the positional arguments, in a function signature the same syntax captures extra positional arguments.

Upvotes: 3

Related Questions