Python回调问题

时间:2018-06-08 15:01:15

标签: 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)

由于

1 个答案:

答案 0 :(得分:0)

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. 您可以在连接顶部添加global ssh,并在根级别命名空间中添加ssh=None