Форум сайта python.su
0
Доброго всем дня!
Помогите разобраться с вот этим кодом
mport os, sys, shutil def copytree(src, dst): for file in os.listdir(src): pathSrc = os.path.join(src,file) pathDst = os.path.join(dst,file) if os.path.isdir(pathSrc): if not os.path.exists(pathDst): os.mkdir(pathDst) copytree(pathSrc, pathDst,) else: shutil.copy2(pathSrc, pathDst) printProgress(i, l, prefix = 'Progress:', suffix = 'Complete', barLength = 50) i+=1 def printProgress (iteration, total, prefix = '', suffix = '', decimals = 2, barLength = 100): filledLength = int(round(barLength * iteration / float(total))) percents = round(100.00 * (iteration / float(total)), decimals) bar = '█' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), sys.stdout.flush() if iteration == total: sys.stdout.write('\n') sys.stdout.flush() items = list(range(0, 100)) l = len(items) i = 0 src = 'E:\\temp\\SampleHTML' dst = 'E:\\temp\\TestMkDir' copytree(src,dst)
C:\Users\>python E:\temp\test.py Traceback (most recent call last): File "E:\temp\test.py", line 42, in <module> copytree(src,dst) File "E:\temp\test.py", line 4, in copytree print(i) UnboundLocalError: local variable 'i' referenced before assignment
Офлайн
0
В функции copytree вы пишете
printProgress(i, l, prefix = ‘Progress:’, suffix = ‘Complete’, barLength = 50)
хотя до этого в функции i никак не задана
Офлайн
0
Так i задана до вызова copytree, i = 0. Как глобальная переменная.
Отредактировано zikfriddi (Июль 30, 2016 18:57:41)
Офлайн
1
вы не можете переопределить внешнюю переменную
i+=1
подразумевает существование i в локальной области
Офлайн
253
kampella1.
вы не можете переопределить внешнюю переменную
def f(): global i i+=1 i=3 f() print(i)
def f(): i=0 while 1: print(i) i+=1
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), sys.stdout.flush() if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
from __future__ import print_function print('.', end="", flush=True)
Отредактировано doza_and (Июль 31, 2016 05:56:36)
Офлайн
0
Спасибо за ответ.
По поводу имени функции, недодумал, исправлю.
Что касается i , как её объявить внутри рекурсивной функции? Или как по другому реализовать прогресс бар?
Офлайн
186
> Что касается i , как её объявить внутри рекурсивной функции?
Передавать как параметр:
def copytree(src, dst, i=0): ... copytree(pathSrc, pathDst, i) ...
Офлайн
0
Я так пробовал, в конце почему-то I у меня равно 0.
Офлайн
186
#!/usr/bin/python # coding: utf-8 import os, sys, shutil def copytree(src, dst): i = 0 for fail in os.listdir(src): pathSrc = os.path.join(src, fail) pathDst = os.path.join(dst, fail) if os.path.isdir(pathSrc): if not os.path.exists(pathDst): os.mkdir(pathDst) copytree(pathSrc, pathDst) else: i += 1 shutil.copy2(pathSrc, pathDst) total = len([ name for name in os.listdir(src) if os.path.isfile(pathSrc) ]) printProgress(i, total, prefix='Progress:', suffix='Complete') def printProgress(iteration, total, prefix='', suffix='', decimals=2, barLength=100): percents = round(float(iteration)/total, decimals)*barLength bar = u'█' * int(percents) + '-' * (barLength-int(percents)) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents/barLength*100, '%', suffix)) sys.stdout.flush() if iteration == total: print('\n') src = '/home/rodegast/0/0' dst = '/home/rodegast/0/1' copytree(src, dst)
Отредактировано Rodegast (Июль 31, 2016 17:12:32)
Офлайн