2014-09-24 3 views
0

Я очень новичок в Stackoverflow и только в начале обучения программированию с Python 3.3. Я просто хотел показать вам свой код со следующим вопросом.Перейти от другого к началу функции

Весь сценарий будет использоваться для копирования копии моего блога с ftp-сервера на локальный жесткий диск.

Я хочу проверить, существует ли уже существующая папка с именем excat. Если да, я хочу подождать 60 секунд и повторить. 60 секунд, потому что после этого исключается, что я сталкиваюсь с той же проблемой.

Я знаю, что вы спросите себя, почему этот чувак будет сделать больше, чем одну копию своего блога в течение одной минуты .. Дело в том, что я хочу, чтобы узнать, как проверить эти ситуации, я мог бы запустить в.

В этом это то, что я пытался, но он не работает:

def create_backup_folder(ftp, destination_directory): 
    temp = time.localtime() 
    current_datetime = "{}-{}-{}_{}-{}".format(temp.tm_year, temp.tm_mon, temp.tm_mday, temp.tm_hour, temp.tm_min) 
    if not os.path.exists(destination_directory + 'bak_' + current_datetime): 
     os.mkdir(destination_directory + 'bak_' + current_datetime, 0o777) 
     print("Backup folder successfully created!") 
    else: 
     print("Folder already exists with the current date_time_stamp. Wait 60 seconds...") 
     time.sleep(60) 
     #create_backup_folder(ftp, destination_directory) 
    newDir = destination_directory + 'bak_' + current_datetime 
    download_directory(ftp, newDir) 

закомментированный-аут линия дает мне ошибку:

AttributeError: 'NoneType' object has no attribute 'sendall' 

Я высоко ценю ваш ответ! Большое спасибо!

+0

Там нет вызова 'sendall' в вашем код; возможно, ошибка в другом месте. – nneonneo

ответ

1

Если вы хотите повторить операцию, цикл for или while внутри функции удобен. В вашем случае вы хотите сделать две попытки, поэтому цикл for работает хорошо. Я попытался привести в порядок Кодекса немного, но вы в конечном итоге с чем-то вроде:

def create_backup_folder(ftp, destination_directory): 
    for i in range(2): 
     temp = time.localtime() 
     current_datetime = "{}-{}-{}_{}-{}".format(temp.tm_year, temp.tm_mon, temp.tm_mday, temp.tm_hour, temp.tm_min) 
     target_dir = destination_directory + 'bak_' + current_datetime 
     if not os.path.exists(target_dir): 
      os.mkdir(target_dir, 0777) 
      print("Backup folder successfully created!") 
      return target_dir 
     else: 
      time.sleep(60) 
    else: 
     raise Exception("Could not create backup directory in two tries") 
0

Переместить петлю за пределами функции, например .:

def create_backup_folder(ftp, destination_directory): 
    temp = time.localtime() 
    current_datetime = "{}-{}-{}_{}-{}".format(temp.tm_year, temp.tm_mon, temp.tm_mday, temp.tm_hour, temp.tm_min) 
    if not os.path.exists(destination_directory + 'bak_' + current_datetime): 
     os.mkdir(destination_directory + 'bak_' + current_datetime, 0o777) 
     print("Backup folder successfully created!") 
     return True 
    else: 
     print("Folder already exists with the current date_time_stamp. Wait 60 seconds...") 
     return False 
    newDir = destination_directory + 'bak_' + current_datetime 
    download_directory(ftp, newDir) 


done = False 
while not done: 
    done = create_backup_folder(foo, bar) 

Я также рекомендую придумывают какие-то условия завершения, так что он не работает вечно.

+0

Я тоже попробовал ваше решение, но распался, потому что не смог вызвать функцию 'download_directory (ftp, newDir)'. Я пробовал несколько позиций, но всегда застрял. В любом случае, спасибо! –

0

Я был в состоянии успешно построить в предложении tdelaney в в моем сценарии.

Вот полное решение этого:

(я просто должен был поставить призыв Funtion create_backup_folder в 2 цикла)

# Create backup folder with date and time stamp 
def create_backup_folder(ftp, destination_directory): 
    for i in range(2): 
     temp = time.localtime() 
     current_datetime = "{}-{}-{}_{}-{}".format(temp.tm_year, temp.tm_mon, temp.tm_mday, temp.tm_hour, temp.tm_min) 
     target_dir = destination_directory + 'bak_' + current_datetime 
     if not os.path.exists(target_dir): 
     os.mkdir(target_dir, mode=0o777) 
     print("Backup folder successfully created!") 
     download_directory(ftp, target_dir) 
     #return target_dir 
     else: 
      print("Please be patient") 
      time.sleep(60) 
    else: 
     raise Exception("Could not create backup directory in two tries") 
Смежные вопросы