I have FTP code which I'm testing with __name__ == '__main__' method which works in certain condition and fails on other. This is basically doing FTP to a site with user name password and then traverse into a Directory where we need to inlist the files using ftplib module. Along with I have kept the exception handling if could not find the Files in the Dir path then come with a error.
#!/usr/bin/python3
import ftplib
from ftplib import FTP
def FtpMirroList():
with FTP("ftp.rraka.com") as ftp:
ftp.login("rar1", "Hf090rFD")
ftp.cwd("mirror/Nimble/1522_rc/optimize_gather/")
#ftp.retrlines('LIST')
try:
FileList = ftp.retrlines('LIST')
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print("No files in this directory")
else:
raise
def main():
for files in FtpMirroList():
print(files)
#main()
if __name__ == '__main__':
FtpMirroList()
When I execute this without main() which I have hashed in the code then it runs fine.
$ ./ftplib-example-4.py
total 19535864
-rw-r--r-- 1 rar1 ftpsecure 9963085277 Jan 09 07:09 15.22.s039.20180109-043530_pslv3.tar.gz
-rw-rw-r-- 1 rar1 ftpsecure 387 Jan 09 06:02 15.22.s039.20180109-043530_pslv3.tar.gz.README
-rw-rw-r-- 1 rar1 ftpsecure 9963166015 Jan 09 14:08 15.22.s039.20180109-164514_pslv3.tar.gz
-rw-rw-r-- 1 rar1 ftpsecure 387 Jan 09 14:11 15.22.s039.20180109-164514_pslv3.tar.gz.README
If I will run this code with main() then it will produce the Error for 'NoneType' object as follows:
Traceback (most recent call last):
File "./ftplib-example-4.py", line 22, in <module>
main()
File "./ftplib-example-4.py", line 19, in main
for files in FtpMirroList():
TypeError: 'NoneType' object is not iterable
Please advise best practice to use with __name__ == '__main__' method while using with functions and calling main().
What i see there is no need of the second function... after editing it works as expected
#!/usr/bin/python3
import ftplib
from ftplib import FTP
def FtpMirroList():
with FTP("ftp.rraka.com") as ftp:
ftp.login("rar1", "Hf090rFD")
ftp.cwd("mirror/Nimble/1522_rc/optimize_gather/")
#ftp.retrlines('LIST')
try:
FileList = ftp.retrlines('LIST')
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print("No files in this directory")
else:
raise
for files in FileList:
print(files)
if __name__ == '__main__':
FtpMirroList()
for files in FtpMirroList()- that's the line with the error (the exception says exactly what kind of error), so if you don't call it (withmain(), since it's in the function called "main"..), the error "won't occur". The practice is to identify and fix broken code. (Hint: what doesFtpMirrorListreturn?) - user2864740main()i i saw in my code.. i'm already reading over the pyton doc - krock1516