问题
So I am trying to set up a small script in Python's IDLE. The IDLE syntax check tells me this code has a syntax error:
from ftplib import FTP
import os
def ftpconnect(address, username, password):
ftp_connection = 0
ftp = FTP(address)
try:
ftp.login(username, password)
print(ftp.getwelcome())
if ftp.getwelcome() == '220 FTP Connected!':
return 1
else:
return 0
print(ftpconnect('10.10.10.xxx', 'xxx', 'xxx'))
The syntax error comes anywhere that I try to get out of the "try" statement, here being the "else:" line. I've looked around and it seems like I have the right syntax...any thoughts?
Thanks! I'm running Python 2, not 3.
回答1:
Alright, I figured it out on my own. The problem was not with my syntax, it was with the my ftp attempt. The line that says "ftp = FTP(address)" was the one I needed to put inside a try: statement, and since I was not "try"ing it, it failed anyway. The reason I was getting a syntax error I believe is because I was using else, rather than except.
来源:https://stackoverflow.com/questions/24520523/python-try-except-else-invalid-syntax