Python 回调的问题



我想我的方式是错误的,我对Python很陌生,所以在得到了一些建议之后。我有一个连接到远程服务器的程序(或尝试(收集一些信息并保存它。在此之前,用户输入 IP 并按连接。我把所有不相关的东西都剪掉了,把里面的肉都留下了。

def connect():
ssh = paramiko.SSHClient()
#paramiko.util.log_to_file("filename.log")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip.get(), username=username, password=password, timeout=5)
except paramiko.SSHException:
text_box.insert(INSERT,"Connection error: Unable to open a connection to ")
#  Display  Connected in the gui:
ip_con_status.delete(1.0, END)
ip_con_status.insert(INSERT,"Connected")
get_but.config(state=NORMAL)
def getinfo():
stdin, stdout, stderr = ssh.exec_command("ls",  timeout=5)
# Display the remote shell's GUI text output:
info = stdout.read()
text_box.insert(INSERT,info)

# Create window
masterwindow = Tk()
masterwindow.minsize(windowx,windowy)
masterwindow.geometry('{}x{}+{}+{}'.format(windowx, windowy, windowxpos, windowypos))
# Create text window and attach scrollbar
tboxw = windowx-200
tboxh = windowy-200
scroll = Scrollbar(masterwindow)
scroll.pack(side=RIGHT, fill=Y)
textfont = ('consolas', 10)
text_box = Text(masterwindow, wrap=WORD, height=22, width=141)
text_box.config(font=textfont)
text_box.config(yscrollcommand=scroll.set)
text_box.place(x = 10, y = 40)
scroll.config(command=text_box.yview)
# Connect button
ip_y = ip_y+25
con_but = Button(masterwindow, text="Connect", state=DISABLED, padx=17, command=connect)
con_but.place(x = ip_x, y = ip_y)
# Get button
ip_y = ip_y+65
get_but = Button(masterwindow, text="Get", state=DISABLED, padx=20, command=getinfo)
get_but.place(x = ip_x, y = ip_y)

那么为什么对"getinfo"的回调不起作用。我必须再次包括:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip.get(), username=username, password=password, timeout=5)

谢谢

ssh 仅在一个函数中定义...这是开始了解命名空间的好时机

def fn(a,b,c):
x=a
fn(22,33,44)
# there is no X it only exists inside of fn

同样

def connect():
ssh = paramiko.SSHClient()
#paramiko.util.log_to_file("filename.log")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip.get(), username=username, password=password, timeout=5)
except paramiko.SSHException:
text_box.insert(INSERT,"Connection error: Unable to open a connection to ")
#  Display  Connected in the gui:
ip_con_status.delete(1.0, END)
ip_con_status.insert(INSERT,"Connected")
get_but.config(state=NORMAL)

仅在其函数内部定义 ssh ...

您有几个选择

  1. 您可以创建一个类来维护状态
  2. 你可以有一些包含状态的全局字典
  3. 您可以在 Connect 的顶部添加global ssh,也可以在根级别命名空间中添加ssh=None

最新更新