Python 3 FTP脚本try-except语法错误排查求助
问题分析与解决
嘿,这个问题很常见!你遇到的语法错误和两个小问题有关,我来帮你一一修正:
1. 最核心的语法错误:Python 3 异常捕获语法变化
你写的 except ftplib.error_perm, resp: 是Python 2 的旧语法,Python 3 已经把异常捕获的语法改成了用 as 来绑定异常对象,正确的写法应该是:
except ftplib.error_perm as resp:
这就是你当前报错的直接原因,Python 3 不再支持逗号分隔异常类型和变量的写法了。
2. 拼写小错误:printi 应该是 print
代码里的 printi("No files in this directory") 和 printi(f) 都是笔误,Python 里没有 printi 这个内置函数,应该改成标准的 print()。
修正后的完整代码
#!/usr/bin/env python3 import ftplib def FtpMirroList(): ftp = ftplib.FTP("ftp.example.com") ftp.login("lodgy", "pass123") ftp.cwd("/my/research/folder") files = [] try: files = ftp.nlst() except ftplib.error_perm as resp: if str(resp) == "550 No files found": print("No files in this directory") else: raise for f in files: print(f) FtpMirroList()
另外顺便提一句,脚本开头的 #!/usr/bin/python env 应该改成 #!/usr/bin/env python3,这样能确保系统调用正确的 Python 3 解释器,避免环境混乱。
内容的提问来源于stack exchange,提问作者krock1516
相关产品推荐
相关产品推荐

