Найти - Пользователи
Полная версия: Проблема с прогресс баром
Начало » Python для новичков » Проблема с прогресс баром
1
zikfriddi
Доброго всем дня!
Помогите разобраться с вот этим кодом
 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

Почему так происходит?
frakite
В функции copytree вы пишете
printProgress(i, l, prefix = ‘Progress:’, suffix = ‘Complete’, barLength = 50)

хотя до этого в функции i никак не задана
zikfriddi
Так i задана до вызова copytree, i = 0. Как глобальная переменная.
kampella
вы не можете переопределить внешнюю переменную
i+=1
подразумевает существование i в локальной области
doza_and
kampella
вы не можете переопределить внешнюю переменную
1.
 def f():
    global i
    i+=1
i=3
f()
print(i)
2.
Имя copytree уже занято https://docs.python.org/2/library/shutil.html.
3.
Такое использование глобальной переменной плохой стиль. У вас оно совершенно непонятно зачем используется.
 def f():
    i=0
    while 1:
        print(i)
        i+=1

Это похоже на огород. print достаточен.
    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)
zikfriddi
Спасибо за ответ.

По поводу имени функции, недодумал, исправлю.
Что касается i , как её объявить внутри рекурсивной функции? Или как по другому реализовать прогресс бар?
Rodegast
> Что касается i , как её объявить внутри рекурсивной функции?

Передавать как параметр:
 def copytree(src, dst, i=0):
    ...
    copytree(pathSrc, pathDst, i)
    ...
zikfriddi
Я так пробовал, в конце почему-то I у меня равно 0.
Rodegast
 #!/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)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB