python基础篇 18-os模块 sample模块 random模块练习例子 sys模块 pip

1、写一个删除日志的脚本,把三天前的日志并且为空的日志删除
生成日志脚本
def timestamp_to_str(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    '''时间戳转格式化好的时间,如果没有传时间戳,就获取当前的格式化时间'''
    if timestamp:
        time_tuple = time.localtime(timestamp) #把时间戳转成时间元组
        result = time.strftime(format,time_tuple) #把时间元组转成格式化好的时间
        return result
    else:
        return time.strftime(format)


import time,os,random
l = ['ios','android','nginx','tomcat','python','blog','apache','mysql','redis']

for i in l:
    p = os.path.join('logs',i)
    os.makedirs(p)
    for j in range(30):
        t = int(time.time())-86400*j
        time_str = timestamp_to_str(t,'%Y-%m-%d')
        log_name = '%s_%s.log'%(i,time_str)
        abs_file_path = os.path.join('logs',i,log_name)
        fw = open(abs_file_path, 'w', encoding='utf-8')
        if random.randint(1,10)%2==0:
            fw.write('胜多负少防守打法双方都')
        fw.close()

 

时间戳 和 日期相互转换函数:
import time

def timestamp_to_str(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    '''
    时间戳转换为格式好的日期格式,如果没有传时间戳,则按照format格式返回当前时间字符串
    :param timestamp:
    :param format:
    :return:  time_str
    '''
    if timestamp:
        time_tuple = time.localtime(timestamp)      # 把时间戳转换为时间元组  获取当前时区的时间戳
        return time.strftime(format,time_tuple)     # 把时间元组 转换为 格式化好的日期
    return time.strftime(format)

def str_to_timestamp(str_time=None,format='%Y-%m-%d %H:%M:%S'):
    '''
    日期字符串转换为时间戳,如果没传日期,则取当前时间的时间戳
    :param str_time:
    :param format:
    :return: timestamp
    '''
    if str_time:
        time_tuple = time.strptime(str_time,format)     # 将日期转换为 时间元组
        return int(time.mktime(time_tuple))                  # 将时间元组 转换为 时间戳
    return int(time.time())

 


clear_log函数:
def clear_log(log_path,interval=3):
    if os.path.isdir(log_path):
        delete_file_sum = 0
        for cur_path,dirs,files in os.walk(log_path):
            for file in files:
                if file.endswith('.log'):
                    file_abs_path = os.path.join(cur_path,file)
                    file_size = os.path.getsize(file_abs_path)
                    if not file_size:
                        str_date = file.split('_')[1].split('.')[0]
                        cur_timestamp = int(time.time())
                        before_timestamp = cur_timestamp - interval * 24 * 3600
                        file_timestamp = str_to_timestamp(str_date,'%Y-%m-%d')
                        if file_timestamp <= before_timestamp:
                            os.remove(file_abs_path)
                            delete_file_sum += 1
                            print(f"删除文件{file_abs_path},文件大小为:{file_size},文件日期为:{str_date}")
                else:
                    pass
        print(f"总共删除文件:{delete_file_sum}个!")
    else:
        print(f"{log_path}不是文件夹!")

 

2、写一个产生双色球号码的程序,输入几就产生多少组
1、每次产生的里面不能有重复的
2、产生的号码要 1 2 3 4 5 6 7
1-32
1-17
01 02 03 04 05 06 07
  其中每组红色球 6个 需要排序 蓝色1个 在最末尾
解决方案1:直接通过random.randint(1,33) 随机取 n 次
import random
def seq(num):
    if str(num).isdigit() and int(num) >0:
        num = int(num)
        s = set()
        while len(s) < num:
            red = sorted([str(random.randint(1,32)).zfill(2) for _ in range(1,7)])
            # print(red)
            blue = [str(random.randint(1,17)).zfill(2) for _ in range(1, 2)]
            ball = ' '.join(red + blue) + '\n'
            s.add(ball)

        with open(r'ball.txt','w',encoding='utf-8') as fw:
            fw.writelines(s)

    else:
        print(f"请输入{num}为正整数")

 

解决方案2:先产生序列 在随机取

import random

reds = [ str(ball).zfill(2) for ball in range(1,34)]
blues = [ str(ball).zfill(2) for ball in range(1,18)]

print(reds)
print(blues)

def seq():
    number = input('number:').strip()
    if number.isdigit() and int(number)>0:
        l = set()
        while int(number)!=len(l):
            red = random.sample(reds,6)
            red.sort()
            blue = random.sample(blues,1)
            result = red + blue
            seq = ' '.join(result)+'\n'
            l.add(seq)
            # print中有重复 输出
            print('生成的双色球号码是:红球:%s 蓝球是:%s'%(' '.join(result[:6]),result[-1]))

    with open('seq.txt','w',encoding='utf-8') as fw:
        fw.writelines(l)

 

3、sys模块
import sys
print(sys.argv)   #用来获取运行python文件的时候,传过来的参数

运行使用:

D:\xxx\xxx2020\day6>python sys模块.py 0
['sys模块.py', '0']
0

注意:index=0的参数 是文件名    index=1的参数 才是第一个入参

例子:

import sys
import os

command = sys.argv[1]
if command == 'install':
    model_mame = sys.argv[2]
    print('install %s' % model_mame)
elif command == 'freeze':
    os.system('pip freeze')
else:
    print('目前只支持 install 和 freeze')

#备份数据库。xxx  ip  user password db

os.system('python bak_db.py 118.23.4.30  root 1234565 test')
# python bak_db.py 118.23.4.30  root 1234565 test

#python toos.py clean_log

4、退出执行的程序

# 退出当前执行python 文件
quit()
exit()

 

 






















posted @ 2021-12-26 20:43  捞铁  Views(53)  Comments(0Edit  收藏  举报