【问题标题】:Python else issues making an FTP programPython else 在制作 FTP 程序时出现问题
【发布时间】:2014-10-09 20:07:08
【问题描述】:

我对这个程序的 else 语句有疑问...我检查了我的间距,它似乎是正确的。我不断收到 else 语句的语法错误。程序创建并文件然后尝试将其上传到 ftp 服务器,但如果它没有对用户说任何内容并继续,它将在程序循环时再次尝试。您能提供的任何帮助将不胜感激。

#IMPORTS
import ConfigParser
import os
import random
import ftplib
from ftplib import FTP
#LOOP PART 1
from time import sleep
while True:
    #READ THE CONFIG FILE SETUP.INI
    config = ConfigParser.ConfigParser()
    config.readfp(open(r'setup.ini'))
    path = config.get('config', 'path')
    name = config.get('config', 'name')
    #CREATE THE KEYFILE
    filepath = os.path.join((path), (name))
    if not os.path.exists((path)):
        os.makedirs((path))
    file = open(filepath,'w')
    file.write('text here')
    file.close()
    #Create Full Path
    fullpath = path + name
    #Random Sleep to Accomidate FTP Server
    sleeptimer = random.randrange(1,30+1)
    sleep((sleeptimer))
    #Upload File to FTP Server
    try:
        host = '0.0.0.0'
        port = 3700
        ftp = FTP()
        ftp.connect(host, port)
        ftp.login('user', 'pass')
        file = open(fullpath, "rb")
        ftp.cwd('/')
        ftp.storbinary('STOR ' + name, file)
        ftp.quit()
        file.close()
        else:
            print 'Something is Wrong'
    #LOOP PART 2
    sleep(180.00)

【问题讨论】:

  • 你的意思是except?!
  • 我的理解是我需要使用 else...在编程方面我有点新手
  • 1.将else: 替换为except Exception: 2。except Exception: 应与try: 处于同一缩进级别
  • 谢谢你成功了...我为这个问题道歉,但这对我来说是新领域...再次感谢

标签: python if-statement syntax ftp try-catch


【解决方案1】:

else 作为异常块的一部分是有效的,但它仅在未引发异常并且必须在其之前定义 except 时运行。

(edit) 大多数人跳过 else 子句,只是在退出 try/except 子句后编写代码。

快速教程是:

try:
    # some statements that are executed until an exception is raised
    ...
except SomeExceptionType, e:
    # if some type of exception is raised
    ...
except SomeOtherExceptionType, e:
    # if another type of exception is raised
    ...
except Exception, e:
    # if *any* exception is raised - but this is usually evil because it hides
    # programming errors as well as the errors you want to handle. You can get
    # a feel for what went wrong with:
    traceback.print_exc()
    ...
else:
    # if no exception is raised
    ...
finally:
    # run regardless of whether exception was raised
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2021-07-01
    • 2021-12-03
    • 2021-04-28
    • 2021-10-30
    相关资源
    最近更新 更多