7-30模块:time、datetime、random、os、subprocess、sys

今日内容
    一 time与datetime模块
    二 random模块
    三 os模块
    四 sys模块

    五 shutil模块
    六 shelve模块
    七 xml模块


    八 suprocess模块

    九 configparser模块
    十 logging模块
    十一 re模块



==========================> time模块======================
			import time

一:时间有三种格式(*****)
	
	
	1、时间戳(float 类型):秒数 ===> 用于时间计算
		缺省时,默认是当前的时间

			start=time.time()
			print(start,type(start))


	2、结构化的时间(struct_time 类型) ===> 获取时间的某一部分
		将时间零散的拆分成各个部分

			res = time.localtime()
			res1 = time.gmtime()

			print(res,type(res))
			print(res.tm_year)

			print(res)
			print(res1)
	

	3、格式化的字符串时间(str 类型) ===> 用于显示给人看
		遵循一定格式组织的时间
		
		gmtime 世界标准时间

		localtime 当地时间

			%p 显示 上午、下午
					am   pm 

				res=time.strftime("%Y-%m-%d %H:%S:%M %p")
				res=time.strftime("%Y-%m-%d %X")
				print(res,type(res))


二:时间转换
	
	格式化的字符串 是另外两者的中介



						localtime:缺省,则当前
					    gmtime						       strftime
		  ---------------------->		      ---------------------->
	时间戳(timestamp)			  结构化的时间(struct_time)		      格式化的字符串时间(Format String)
		  <----------------------		      <----------------------
	  		maktime					   		    strptime	 	   
	


	转换用到的函数:
	  		
		1、localtime([secs]) : 将一个时间戳转换为当前时区的struct_time。
								secs参数未提供,则以当前时间为准。
					
					time.localtime()
 					time.localtime(1473525444.037215)
		
		2、gmtime([secs]) : 将一个时间戳转换为UTC时区(0时区)的struct_time
							和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。



		3、mktime(t) : 将一个struct_time转化为时间戳。

					print(time.mktime(time.localtime()))#1473525749.0


		4、strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和 time.gmtime()返回)转化为格式化的时间字符串。
									如果t未指定,将传入time.localtime()。
									如果元组中任何一个元素越界,ValueError的错误将会被抛出。

					print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56


		5、strptime(string[, format]) : 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。

					print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))

	
		6、time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
  															tm_wday=3, tm_yday=125, tm_isdst=-1)
 				在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。



	2.1 时间戳--->格式化的字符串

			struct_time=time.localtime(3333.3)
			res=time.strftime("%Y:%m",struct_time)
			print(res)

	2.2 格式化的字符串时间--->时间戳

			struct_time=time.strptime("2017-07-03 11:11:11","%Y-%m-%d %H:%M:%S")
			res=time.mktime(struct_time)
			print(res)

三:
 	asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。
 						如果没有参数,将会将time.localtime()作为参数传入。

 			print(time.asctime())#Sun Sep 11 00:43:43 2016
			print(time.asctime(time.localtime(3333.3)))

	ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。
						如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。

			print(time.ctime())  # Sun Sep 11 00:46:38 2016
			print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016
			print(time.ctime(3333.3))


四: sleep(secs) : 线程推迟指定的时间运行,单位为秒。
			
			time.sleep(3)

==========================> datetime模块========================
		import datetime

1、获取当前时间
		print(datetime.datetime.now())


2、时间戳---转成--->日期格式

	3、只显示日期:
		print(datetime.date.fromtimestamp(time.time()))
		# 2020-07-30

	4、显示日期+时分
		print(datetime.datetime.fromtimestamp(time.time()))
		# 2020-07-30 16:20:58.497910

5、加时间
		print(datetime.datetime.now() + datetime.timedelta(days=3))

6、减时间
		print(datetime.datetime.now() + datetime.timedelta(days=-3))

7、替换时间
		print(datetime.datetime.now())
		new_res=res.replace(year=1999,month=9)
		print(new_res)

==========================> random模块 <=============================

			import random

	# os.path.以下各个函数

random模块中的常用函数:

	1、random(): 随机 产生一个小数 (0,1)    
				print(random.random())
				#大于0且小于1之间的小数

	2、randint(): 随机 产生一个整数 [a,b]		 
			
				print(random.randint(1,3)) #[1,3]

	3、choice(): 随机 选取一个元素
			
				print(random.choice([1,'23',[4,5]]))

	4、sample(): 随机 选取列表中任意2个元素进行组合
			
				print(random.sample([1,'23',[4,5]],2))

	5、uniform(): 随机 产生一个小数(a,b) 
				
				print(random.uniform(1,3))
				# 大于1小于3的小数,如1.927109612082716

	6、shuffle(): 打乱列表中元素的顺序,相当于"洗牌"
			
			item=[1,3,5,7,9]
			random.shuffle(item)
			print(item)


	

随机验证码原理:随机的字母 、随机的数字    里面挑选一个作为一个结果

		def make_code(n=5):
		    res = ''
		    for i in range(n):
		        s1 = str(random.randint(0, 9))	# 产生数字
		        s2 = chr(random.randint(65, 90)) # 产生字母
	            # 每一轮生成一个数字or字母,将他们连接在总的字符串上
		        res += random.choice([s1, s2])
		    return res

		print(make_code(4))


========================> os模块 <===============================

os模块是与操作系统交互的一个接口
在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。

	import os

	# os.path.以下各个函数

os.path下的常用函数

	1、dirname(): 返回path的目录。【推荐此方式!】
					其实就是os.path.split(path)的第一个元素

			print(os.path.dirname("D:/python全栈15期/day21/03os模块.py"))

		2、normpath(): 返回path的路径,【不推荐此方式!】
			
			res=os.path.join(
			    __file__,
			    "..",
			    ".."
			)

			print(os.path.normpath(res))

	3、basename(): 返回path最后的文件名。
					如果path以/或\结尾,那么就会返回空值。
				  	即os.path.split(path)的第二个元素

			print(os.path.basename("D:/python全栈15期/day21/03os模块.py"))

	4、join(): 将多个路径组合后返回,
			  	第一个绝对路径之前的参数将被忽略

			print(os.path.join("a",'b','D:\c','d.txt'))

	5、isabs():判断是否是绝对路径

			print(os.path.isabs("D:/python全栈15期/day21/"))
			print(os.path.isabs("/python全栈15期/day21/"))

	6、rename():  重命名文件/目录

	7、remove(): 删除一个文件

	8、split(path): 将path分割成目录和文件名二元组返回

	9、getsize(): 返回该文件/文件夹的大小

	10、exists(): 判断路径是否存在  
					如果path存在,返回True;如果path不存在,返回False
			
			print(os.path.exists("D:/python全栈15期/day21/"))

	11、isfile(): 判断文件是否存在  
					如果path是一个存在的文件!文件!文件!,返回True。否则返回False

	12、isdir(): 判断目录是否存在
					如果path是一个存在的目录!目录!目录!,则返回True。否则返回False

	13、split(): 将path分割成目录和文件名二元组返回

	14、listdir('dirname'): 列出指定目录下的所有文件和子目录,
							  包括隐藏文件,并以列表方式打印







模拟windows的cmd.exe终端:

		import os
		print(os.listdir("."))

		import os

		cmd=input(r"""
		Microsoft Windows [版本 10.0.17763.1339]
		(c) 2018 Microsoft Corporation。保留所有权利。

		%s=====> """ %os.getcwd())
		res=os.system(cmd)
		print('='*100)
		print(res)


		import os
		print(__file__)
		print(os.path.abspath(__file__))

		res=os.path.split("D:/python全栈15期/day21/03 os模块.py")
		# 用于将 所在的文件夹的路径,和文件名 相分割开,存进元组里面
		print(res)
	

======================>  subprocess模块 <=================================

		import subprocess

		# pwd ; sasdfasdf ;echo 123

		obj = subprocess.Popen("**这里是命令名称**", shell=True,
		                       stdout=subprocess.PIPE,
		                       stderr=subprocess.PIPE
		                       )

		res1=obj.stdout.read()
		res2=obj.stderr.read()
		# print(res1.decode('gbk'))
		print(res2.decode('gbk'))


不同的进程,都有只属于自己的内存空间(这是物理隔离);进程不能访问其他进程的内存空间(安全保护机制)

为满足  不同进程之间的通信(数据共享)的需求,开辟的共享内存

管道 属于共享内存;不同的进程都可以访问这块内存

操作系统命令的结果默认 是直接返回到终端,

通过将结果,接收放到管道,可以对 结果进行处理

----------




应用程序  的命令 都是调用 操作系统的命令,来执行服务

windows提供的cmd.exe也是一个操作系统的提供的一个应用程序

一个windows系统命令,就是一个程序


命令运行程序格式   以空格为分隔符
	
解释器	程序名   +	传入的参数


	也相当于,input方式,一次输入一个参数
	相比较而言,这种写在一行的形式,更为简洁
	区别在于,传入程序所需要的参数 的方式


在windows的cmd中  由于windows命令是.exe直接运行的文件,所以不需要加解释器

而要运行 .py文件的话,则需要加python解释器


sys.argv 将参数采集 命令行中传入的参数, 用索引[index]来区分采集的是哪一个参数


永久的配置 写到 配置文件中
临时的配置 通过 传入参数



======================sys模块==========================


		import sys

		sys.path
		print(sys.argv)

		src_file = input("源文件路径:").strip()
		dst_file = input("目标文件路径:").strip()
		src_file = sys.argv[1]
		dst_file = sys.argv[2]

		with open(r"%s" %src_file,mode='rb') as f1,open(r"%s" %dst_file,mode='wb') as f2:
		    for line in f1:
		        f2.write(line)



实现打印进度条=====================

原理:通过静态的方案实现动态的效果


原理阐述:
		import time
		print("[#               ]",end='')
		time.sleep(0.3)
		print("\r[##              ]",end='')
		time.sleep(0.3)
		print("\r[###             ]",end='')
		time.sleep(0.3)
		print("\r[####            ]",end='')


		print("[%-15s]" % "###",)
		print("[%-15s]" % "####",)



实现代码:
		import time

		def progress(percent):
		    if percent > 1:
		        percent=1

		    # 第二个%号代表取消第一个%的特殊意义 
		    # -50用来控制对齐方式、宽度
		    print("\r[%-50s] %d%%" % ("#"*int(50*percent),int(100 * percent)),end='')

		total_size = 1025
		recv_size = 0

		while recv_size < total_size:
		    
		    # 每次下载1024
		    time.sleep(0.3)

		    #模拟数据的传输延迟
		    recv_size+=1024

		    #接收的比例
		    percent = recv_size / total_size

		    progress(percent)




\r  是在行首打印

进度条的原理:用 静态 模拟出 动态 效果
替换整体静态,速度很快时,就成了动态


% 的优先级比 * 高
    在进度条中,要使用括号,标注优先级


1 sys.argv           命令行参数List,第一个元素是程序本身路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值