Извлечение значения функции: как получить доступ к значению переменной вне функции. и как использовать это значение в другой функции? - PullRequest
1 голос
/ 25 марта 2019

Я написал код для печати IP-адреса, соответствующего указанному mac-адресу.дело в том, что IP находится внутри функции retrieve_input.Как я могу получить значение IP вне функции retrieve_input?Вот мой код.

from tkinter import *
import subprocess

window = Tk()
window.title("Welcome..")
a = str(subprocess.getoutput(["arp", "-a"]))
print(a)
text=a
def retrieve_input():                   #retrive input and fetches the IP
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2]
        print(ip)

window.geometry('900x700')
lbl1=Label(window, text="MAC ADDRESS",width=15,height=2,font=2)
lbl1.grid(column=0, row=0)
txt=Text(window, width=25,height=1)
txt.grid(column=1, row=0)
btn = Button(window, text="CONVERT",fg="black",bg="light 
grey",width=15,font=4,height=2,command=lambda:(retrieve_input())
btn.grid(column=1, row=2)

window.mainloop()

Ответы [ 2 ]

2 голосов
/ 25 марта 2019
def retrieve_input():                   #retrive input and fetches the IP
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2]
        return ip
    else:
        return False

ip_value = retrieve_input()

Вы можете использовать return IP, если вы не хотите использовать глобальные переменные, с этой функцией можно возвращать IP адреса, которые вы хотели бы использовать.

Однако есть другой подход, если вы знаете классы и атрибуты Python.

class IpValues:

    def __init__ (self):
        # Initialize and use it as constructor
        self.ip = None
        pass

    def retrieve_input(self):                   
        # retrive input and fetches the IP
        inputValue=txt.get(1.0, "end-1c")
        ext = inputValue
        if (inputValue in a and inputValue != ''):
            nameOnly = text[:text.find(ext) + len(ext)]
            self.ip = nameOnly.split()[-2]


ip_values_object = IpValues()
ip_values_object.retrieve_input()
print(ip_values_object.ip)
0 голосов
/ 25 марта 2019

Вы можете сделать ip глобальной переменной следующим образом:

def retrieve_input():
  global ip #declare ip as a global variable                   
  ip = "0.0.0.0" #assign a value to ip

retrieve_input()
print(ip) #access the value of ip outside the function

В вашем коде это будет выглядеть так:

def retrieve_input():
    global ip #declare ip as a global variable
    inputValue=txt.get(1.0, "end-1c")
    ext = inputValue
    if (inputValue in a and inputValue != ''):
        nameOnly = text[:text.find(ext) + len(ext)]
        ip = nameOnly.split()[-2] #assign a value to ip
        print(ip)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...