大家在安装程序或下载文件时,通常都能看到进度条,提示你当前任务的进度。其实,在python中实现这个功能很简单,下面是具体代码。在实际应用中,你完全可以根据自己的要求进行修改!比如,示例中是通过time.sleep()方法进行时间延迟,你完全可以根据实际的程序运行耗时进行控制;同样,在进度百分比处,你也可以显示实际的进度比,而不是例子中机械的自增百分比。
import sys
import time
def view_bar(num, total):
rate = num / total
rate_num = int(rate * 100)
r = 'r[%s%s]%d%%' % ("="*num, " "*(100-num), rate_num, )
sys.stdout.write(r)
sys.stdout.flush()
if __name__ == '__main__':
for i in range(0, 101):
time.sleep(0.1)
view_bar(i, 100)
再给大家分享一个方法
import hashlib
a = "a test string"
print hashlib.md5(a).hexdigest()
print hashlib.sha1(a).hexdigest()
print hashlib.sha224(a).hexdigest()
print hashlib.sha256(a).hexdigest()
print hashlib.sha384(a).hexdigest()
print hashlib.sha512(a).hexdigest()
再来一个复杂点的函数吧
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import threading
import time
'''
class Demo:
def __init__(self,thread_num=5):
self.thread_num=thread_num
def productor(self,i):
print "thread-%d start" %i
def start(self):
threads=[]
for x in xrange(self.thread_num):
t=threading.Thread(target=self.productor,args=(x,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print 'all thread end'
demo=Demo()
demo.start()
'''
thread_num=10
def productor(i):
print "thread-%d start" %i
time.sleep(2)
def start():
threads=[]
for x in range(thread_num):
t=threading.Thread(target=productor,args=(x,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print 'all thread end'
start()
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import paramiko
import sys
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
t = paramiko.Transport(('vm_135',22))
# 连接服务器
t.connect(username='root',pkey=private_key)
ssh.connect(hostname='vm_135', port=22, username='root',pkey=private_key)
# 执行命令
sftp = paramiko.SFTPClient.from_transport(t)
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
print result
def progress_bar(transferred, toBeTransferred, suffix=''):
# print "Transferred: {0}tOut of: {1}".format(transferred, toBeTransferred)
bar_len = 60
filled_len = int(round(bar_len * transferred/float(toBeTransferred)))
percents = round(100.0 * transferred/float(toBeTransferred), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%sr' % (bar, percents, '%', suffix))
sys.stdout.flush()
sftp.put("/tmp/134","/tmp/134",callback=progress_bar)
#for filename in filenames:
# sftp.put(os.path.join(dirpath, filename),
# os.path.join(remote_path, filename),
# callback=self.progress_bar)
# print
# print "upload %s/%s" % (remote_path, filename) + 't' + '[' + green("success") + ']'
ssh.close()
以上就是本文的全部内容了,大家是否对使用Python实现带百分比进度条有了新的认识了呢,希望大家能够喜欢。