Python FTP程序中的else问题

2024-04-19 17:07:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这个程序的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)

Tags: pathnameimport程序configosftpsleep
1条回答
网友
1楼 · 发布于 2024-04-19 17:07:01

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

(edit)大多数人跳过else子句,在退出try/except子句(dedenting)后编写代码。你知道吗

快速教程是:

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
    ...

相关问题 更多 >