Unable to call variable from function into python


#1

The below function i saved into a file

def lldp(client1):
    #global A
    stdin, stdout, stderr = client1.exec_command('show lldp neighbor interface' + " " + q[0] + " " + '| match add')
    z = stdout.read()
    A = z.split()
    A = A[9]
    if A == ':':
        sys.exit()
    return

And in above function Variable A will be stored by some value and i wanted to use same A into another script
lldp(client1)
client1.connect(A, username=username, password=password)
If i run this script I am getting below error
NameError: name ‘A’ is not defined - I understand that A is not calling the value from another function but not sure how to fix it. Please help


#2

so difficult to say without the rest of the code, you could return A instead of just return, so then you get:

def lldp(client1):
    #global A
    stdin, stdout, stderr = client1.exec_command('show lldp neighbor interface' + " " + q[0] + " " + '| match add')
    z = stdout.read()
    A = z.split()
    A = A[9]
    if A == ':':
        sys.exit()
    return A

# function call, i have no clue of knowing
# what the argument should be
# so i put in some question marks
A = lldp(???)

but like i said, difficult to say without being able to replicate the problem


#3

Tried with return A but no luck. But in general there will be standard way of calling a variable assigned in a function into script correct ?


#4

then you need to capture the returned result, like i showed you:

A = lldp(???argument???)

you don’t call variables, you call functions

yea, you can return the variable and then capture the returned result

If you need more help, provide a way i can replicate the problem


#5

Let’s try this

def lldp():
A = 9 + 5
return

Below is the script calling above function

from import lldp

lldp()
B = A + 5
print B

I am getting same error

B = A + 5
NameError: name ‘A’ is not defined


#6

Hey

It worked

as you said A = lldp() did the trick.

Thanks alot.


#7

But do you understand why?

I am confused, i already suggested that in my first reply? How was my first reply not good enough? What needed to be better?


#8

Well,

I have not checked it properly. sorry for that.


#9

No problem, good that you figured it out :slight_smile:


#10