I can't seem to be able to change directory past /ubuntu/ on archive.ubuntu.com, and I suspect my code to change to the wrong directory. Where is my bug?
from ftplib import FTP
from tkinter import *
ftp = FTP("archive.ubuntu.com")
ftp.login()
window = Tk()
window.geometry("640x480")
def listdir():
print(ftp.dir())
[child.destroy() for child in window.winfo_children()]
for x in ftp.nlst():
Button(window, text=x, command=(lambda: cdir(x))).pack()
def cdir(x):
f = ftp.pwd()+"/"+x
ftp.cwd(f)
listdir()
listdir()
window.mainloop()
this is simple code to reproduce my problem in my larger application.
system: windows
python runtime: python 3.8
How would it be possible to prevent this bug? I can change directory just fine using python command line. ftplib isn't throwing any errors, I have tried printing every command that I run on ftp.
You'll be wanting early binding in your lambda
function. Change from
lambda: cdir(x)
to:
lambda y=x: cdir(y)
Otherwise you get the value of x
when the function is called, rather than the one when the function was created.
(Obviously you still need to tell your code about the difference between files and directories because with above fix in place you can then get to navigate as far as buttons representing actual files, and clicking on those will give an error when it tries to change directory to them. But the above will fix the issue that you are encountering right now.)