1、安装PIP,并安装第三方包requests,后验证包是否安装成功
pip install requests 安装库
pip list 查看已经安装的库
如果用python3 ,则pip更改为pip3
2、编程习题: 简单抽奖程序
1. 奖池中员工号通过文件输入,文件中每一行一个员工号(自己模拟)
2.在控制台中每 100 毫秒在新行输出一个员工号,模拟滚动效果
3.用户单击回车键,停止滚动,输出中奖员工号码
参考:https://blog.csdn.net/youyouheheda/article/details/51222533
https://cloud.tencent.com/developer/section/1369713
https://blog.csdn.net/zyl_wjl_1413/article/details/84864482
import random
import msvcrt
import linecache
import time
import datetime
# text = linecache.getline('a1.txt',2) #linecache模块,比如你要输出某个文件的第n行
# print(text.rstrip('\n'))
with open ('a1.txt','r') as f :
f = f.readlines()
print(f)
# random.shuffle(lst) shuffle() 方法将序列的所有元素随机排序
while True:
index = random.randint(0, 19)
print(f[index].rstrip('\n')) #rstrip() 删除 string 字符串末尾的指定字符(默认为空格)
if msvcrt.kbhit(): #利用 msvcrt 模块获取键盘输入,利用 kbhit()函数判断是否有键盘输入可读
k = msvcrt.getwch()
if k in '\r': #\r 表示回车符
print('winner is :',f[index])
break
time.sleep(0.1)# 进程延迟命令,变量单位为秒
print(datetime.datetime.now()) #import datetime
3、编程习题:模拟windows dir命令
文件路径的表示方式:
windows下absPath = ' G:\\lzy\\software\\python\\test1'
linux下 absPath = ' G:/lzy/software/python/test1'
参考:https://www.cnblogs.com/dkblog/archive/2011/03/25/1995537.html
import os
import time
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y/%m/%d %H%M', timeStruct)
absPath = 'C:\\Users\\Administrator\\PycharmProjects\\hanshu\\test'
for fileName in os.listdir(absPath):
fileAbsPath = os.path.join(absPath, fileName)
dirModifyTime = TimeStampToTime(os.path.getmtime(fileAbsPath))
isDir = None
dirSize = None
if os.path.isdir(fileAbsPath):
isDir = '<DIR>'
dirSize = ' '
if os.path.isfile(fileAbsPath):
isDir = ' '
dirSize = str(format(os.path.getsize(fileAbsPath), ','))
print(dirModifyTime, isDir.center(5, ' '), dirSize.rjust(8, ' '), fileName)
4、编程习题:模拟windows del命令
import shutil
import argparse
import os
parser = argparse.ArgumentParser(description='this is a sample program') #创建解析
parser.add_argument('-i','--input')
args = vars(parser.parse_args())
print(args['input'])
absPath = 'C:\\Users\\Administrator\\PycharmProjects\\hanshu'
fileAbsPath = os.path.join(absPath,args['input'])
print(fileAbsPath)
if os.path.isdir(fileAbsPath):
os.rmdir(args['input'])
if os.path.isfile(fileAbsPath):
os.remove(args['input'])
5、编程习题:计时器功能
输入日期,根据输入的日期计算倒计时天数
from datetime import datetime
y = input('请输入年份:例1990')
m = input('请输入月份:例04')
d = input('请输入日期:例31')
t1 = datetime.now()
t2 = datetime(int(y),int(m),int(d))
t3 = t2 -t1
print('距离%s-%s-%s 还有%d天'%(y,m,d,t3.days))
输入目标时间,倒计时输出到标准输出,每秒更新一次
import time
count = 0
a = int(input('time:'))
while count < a :
count_now = a - count
print(count_now)
time.sleep(1)
count += 1
print('done')
6、编程习题:日志功能,扩展logging功能
参考:https://www.cnblogs.com/nancyzhu/p/8551506.html
https://www.cnblogs.com/liujiacai/p/7804848.html
输出当前代码文件名称,行,当前时间精确到毫秒
import logging as lg
lg.basicConfig(level=lg.INFO,format = '%(asctime)s - %(filename)s - %(levelname)s - %(message)s - %(lineno)d ')
lg.info('print this lines')
输出:
2019-12-30 20:40:38,707 - test.py - INFO - print this lines - 5
输出信息到标准输出和文件中,文件每小时重新建立一个
import glob
import logging
import logging.handlers
import time
LOG_FILENAME = 'logging_xeample.out'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME,'h',1)
my_logger.addHandler(handler)
for i in range(20):
my_logger.debug('i = %d',i)
logfiles = glob.glob('%s*'%LOG_FILENAME)
for filename in sorted(logfiles):
print(filename)
编写代码:使用doctest测试以下功能的函数:
测试字符串格式化功能
测试collections模块中deque功能
import math
import doctest
def my_function(a,b):
'''
>>> my_function(3,4)
81
'''
return pow(3,4)
print(doctest.testmod())
输出:
TestResults(failed=0, attempted=1)
控制台命令:python -m doctest -v test.py #test.py为python文件名称
import math
import doctest
import collections
d1 = collections.deque()
d1.extend('abcdefg')
def my_function_1(a):
'''
>>> my_function_1(d1)
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
'''
d1.append('h')
return d1
def my_function_2(a):
'''
>>> my_function_2('abcdefg')
'abcdefg '
'''
sp = '%-10s'%a
return sp
print(doctest.testmod())
编写测试类:测试math模块的相关功能
见博客python模块2.7.3