Python正课55 —— sys模块

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12597780.html

一:解析

sys.argv

import sys

# python3 run.py 1 2 3
# sys.argv 获取的是解释器后的参数值
print(sys.argv)

文件拷贝的原始方法

src_file = input('原文件路径:').strip()
dst_file = input('新文件路径:').strip()

with open(r'%s'%src_file, mode='rb') as read_f,\
    open(r'%s'%dst_file, mode='wb') as write_f:
    for line in read_f:
        write_f.write(line)

文件拷贝的新方法

src_file = sys.argv[1]
dst_file = sys.argv[2]

with open(r'%s'%src_file, mode='rb') as read_f,\
    open(r'%s'%dst_file, mode='wb') as write_f:
    for line in read_f:
        write_f.write(line)
# 在run.py所在的文件夹下,按住shift,右键,选择“在此处打开power shell”,输入
# 格式:python3 run.py 原文件路径 新文件路径
# python3 run.py D:\1.docx D:\2.docx   #拷贝成功

二:进度条

# print('[%-50s]' %'#')
# print('[%-50s]' % '##')
# print('[%-50s]' % '###')

# 输出:
[#                                                 ]
[##                                                ]
[###                                               ]
import time

res = ''
for i in range(50):
    res += '#'
    time.sleep(0.2)
    print('\r [%-50s]' % res, end='')
    
# 输出:  [##################################################]

进阶打印进度条

import time
recv_size = 0
total_size = 25600

while recv_size < total_size:
    # 模拟网速
    time.sleep(0.2)
    # 下载了1024个字节的数据
    recv_size += 1024
    # 打印进度条
    # print(recv_size)
    percent = recv_size / total_size    # 1024 / 25600
    if percent > 1:
        percent = 1
    res = int(50 * percent) * '>'
    print('\r [%-50s] %d%%' % (res,percent*100), end='')

再次进阶打印进度条

import time

def progress(percent):
    if percent > 1:
        percent = 1
    res = int(50 * percent) * '>'
    print('\r [%-50s] %d%%' % (res,percent*100), end='')

recv_size = 0
total_size = 25600

while recv_size < total_size:
    time.sleep(0.2)
    recv_size += 1024
    percent = recv_size / total_size    # 1024 / 25600
    progress(percent)
posted @ 2020-03-30 12:26  轻描丨淡写  阅读(289)  评论(0编辑  收藏  举报