将类的变量从func传递到另一个func



我正在使用gui tkinter+netmiko构建一个程序。现在我有了输入字段,按钮"连接",按钮"运行命令"。它做了我需要的事情,打印了一个命令的输出,但每次它都使用connect func并初始化到远程设备的连接。是否可以只连接一次,并在其他函数中使用net_connect变量(它是一个类)?因此,在run_commandfunc中,我只使用connect的返回值,而不调用整个connection函数。我将有几十个带有不同命令的run_command函数。据我所知,我不能使用全局变量。我省略了代码的其余部分。

from tkinter import *
from netmiko import ConnectHandler
def connect():
Router = {'device_type': 'cisco_ios', 'ip': hostname_entry.get(), 'username': 'x', 'password': 'x'}
net_connect = ConnectHandler(**Router)
return net_connect
def run_command():
command = connect()
show_version_output = command.send_command('show version') # here I need to use: *show_version_output = net_connect.send_command*
print(show_version_output)
return show_version_output

我会将ssh_conn作为参数传递:

from tkinter import *
from netmiko import ConnectHandler
def connect():
Router = {'device_type': 'cisco_ios', 'ip': hostname_entry.get(), 'username': 'x', 'password': 'x'}
net_connect = ConnectHandler(**Router)
return net_connect
def run_command(ssh_conn, cmd):
output = ssh_conn.send_command(cmd)
print(output)
return output
if __name__ == "__main__":
ssh_conn = connect()
show_ver = run_command(ssh_conn, cmd="show version")
show_ip_int_br = run_command(ssh_conn, cmd="show ip int brief")

最新更新