python - 函数值检索:如何访问函数外部变量的值。以及如何在另一个函数中使用该值?
问题描述
我编写了一个代码来打印与给定的mac地址对应的IP地址。问题是 IP 在retrieve_input 函数中。如何在retrieve_input 函数之外获取IP 值?这是我的代码。
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()
解决方案
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)
推荐阅读
- python - 根据与熊猫的部分匹配合并列
- python - Numpy多维数组分配未知逻辑错误
- twitter - 为什么 twidge 应用程序给我 E:尝试在 Ubuntu 18.04 上执行 apt-get 时无法找到包 twidge
- json - 是否可以减少快速编码协议的样板代码
- javascript - 如何在 aws cognito 中创建不同的访问级别?
- python - 如何在 Python 3 中将变量设置为随机整数?
- google-bigquery - GCP Bigquery:无法查询在云存储中导出的堆栈驱动程序访问日志,因为无效的 json 字段“@type”
- python - 是否可以在运行 python 程序之前初始化模块?
- python - 在 Python 类中获取变量类型
- c# - asp.net-core - 有没有办法使用 WebHostBuilder 或 TestServer 添加内联剃须刀页面?