2014-10-09 21 views
-2

我遇到了這個程序的else語句的問題......我檢查了我的間距,它似乎是正確的。我一直在else語句上出現語法錯誤。該程序創建並文件,然後嘗試將其上傳到ftp服務器,但是如果它不能向用戶說出任何內容並繼續,則在程序循環時將再次嘗試。任何幫助你可以提供將不勝感激。Python其他問題正在製作一個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) 
+1

您的意思是'except'? – jonrsharpe 2014-10-09 20:08:20

+0

這是我的理解是,我需要使用別的......我有點新手,當涉及到編程 – user3739525 2014-10-09 20:09:54

+1

我可以推薦https://docs.python.org/2/tutorial/errors.html – jonrsharpe 2014-10-09 20:10:32

回答

2

else是作爲異常塊的部分有效,但如果一個異常沒有提出它只是運行,必須有之前定義的except

(編輯)大多數人跳過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 
    ... 
相關問題