如何显示python的内置模块_python3–内置模块

Review

time,datetime 模块

导入:from datetime import datetime

import time

获取时间戳:time.time()

暂停10秒钟time.sleep(10)

获取当前年datetime.now().year //年

datetime.now().month //月

datetime.now().day //日

datetime.now().hour //时

datetime.now().minute //分钟

datetime.now().second //秒

获取昨天的日期import timedelta

yesterday = datetime.now() + timedelta(days=-1)

print(yesterday)

执行linux命令模块

执行ipconfigimport subprocess

subprocess.call("ipconfig")

或者使用 os 模块 获取:import os

os.system("ipconfig")

如何获取这个值呢?(经常会用到)import os

result = os.popen("ipconfig")

print(result.read())

日志记录模块

日志的级别:debug

info

warning

error

critical

● DEBUG:详细的信息,通常只出现在诊断问题上。

● INFO:确认一切按预期运行

● WARNING:一个警告,可能会有一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”)。这个软件还能按预期工作

● ERROR:个更严重的问题,软件没能执行一些功能

● CRITICAL:一个严重的错误,这表明程序本身可能无法继续运行import logging

log = logging.debug("this is a debug mode")

log = logging.info("this is a info mode")

log = logging.warning("this is a warning mode")

log = logging.error("this is a error mode")

log = logging.critical("this is a critical mode")

输出:

WARNING:root:this is a warning mode

ERROR:root:this is a error mode

CRITICAL:root:this is a critical mode

由此可以分析得到,我们的默认终端打印的是warning及以上的信息。

当然有时候我们需要分析全部的日志,需要把日志级别调节到 debug 模式:import logging

logging.basicConfig(level=logging.DEBUG)

log = logging.debug("this is a debug mode")

log = logging.info("this is a info mode")

log = logging.warning("this is a warning mode")

log = logging.error("this is a error mode")

log = logging.critical("this is a critical mode")

输出:

DEBUG:root:this is a debug mode

INFO:root:this is a info mode

WARNING:root:this is a warning mode

ERROR:root:this is a error mode

CRITICAL:root:this is a critical mode

写一个程序,简单介绍下各个错误级别的用法:import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

def hello():

print("hello world!!")

def main():

logger.info("start running hello()")

hello()

logger.info("already start use hello script")

try:

2 / 0

except Exception as e:

logger.error("fenmu cannot use 0")

f = open("demon1.py", "r")

finally:

logger.warning("the file not close")

if __name__ == '__main__':

main()

输出:INFO:__main__:start running hello()

hello world!!

INFO:__main__:already start use hello script

ERROR:__main__:fenmu cannot use 0

WARNING:__main__:the file not close

分析:因为我们日志级别定义的为 DEBUG,所以会输出所有的错误信息:

INFO:__main__:start running hello() //开始执行前

hello world!! //已经执行

INFO:__main__:already start use hello script //已经调用了hello函数

ERROR:__main__:fenmu cannot use 0 //输出错误信息

WARNING:__main__:the file not close //最后执行finally

继续修改:如果把日志级别去掉,也就是使用默认级别:import logging

# logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

def hello():

print("hello world!!")

def main():

logger.info("start running hello()")

hello()

logger.info("already start use hello script")

try:

2 / 0

except Exception as e:

logger.error("fenmu cannot use 0")

f = open("demon1.py", "r")

finally:

logger.warning("the file not close")

if __name__ == '__main__':

main()

输出:(只会打印warning及以上的告警信息)fenmu cannot use 0

hello world!!

the file not close

也就是说,未来在真正的工作中,使用如上这种模式去追踪一个错误还是非常实用的。

当然如果去分析一个很庞大的程序,我们日志的格式也是非常重要的:import logging

logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='myapp.log', filemode='w')

logger = logging.getLogger(__name__)

def hello():

print("hello world!!")

def main():

logger.info("start running hello()")

hello()

logger.info("already start use hello script")

try:

2 / 0

except Exception as e:

logger.error("fenmu cannot use 0")

f = open("demon1.py", "r")

finally:

logger.warning("the file not close")

if __name__ == '__main__':

main()

最主要的是如下:logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='myapp.log', filemode='w')

如上定义了:(从左到右)

- 日志的级别

- 日志的格式:

- 访问时间

- 脚本名

- 执行脚本的行数

- 警告级别

- 警告信息内容

- 时间格式

- log文件相关

具体参数:

主要是通过logging.basicConfig函数进行操作,现在我们来介绍一下该函数参数的用法:

level: 设置日志级别,默认为logging.WARNING

filename: 指定日志文件名。

filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'

format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

%(levelname)s: 打印日志级别名称

%(filename)s: 打印当前执行程序名

%(funcName)s: 打印日志的当前函数

%(lineno)d: 打印日志的当前行号

%(asctime)s: 打印日志的时间

%(thread)d: 打印线程ID

%(process)d: 打印进程ID

%(message)s: 打印日志信息

datefmt: 指定时间格式,同time.strftime()

stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

logging.getLogger([name]):创建一个日志对象:

输出的日志格式为:(当然是生成一个myapp.log的文档)2018/04/25 13:33:17 demon5.py[line:64] INFO start running hello()

2018/04/25 13:33:17 demon5.py[line:66] INFO already start use hello script

2018/04/25 13:33:17 demon5.py[line:70] ERROR fenmu cannot use 0

2018/04/25 13:33:17 demon5.py[line:73] WARNING the file not close

os 内置模块

系统兼容性import os

print(os.name)

如果输出为:nt 则代表着系统是windows系统

如果输出为:posix 则代表着系统是unix系统

小练习:import os

result = os.name

if result == "nt":

print("{0} means: this is a windows system.".format(result))

else:

print("{0} means: this is a unix system".format(result))

输出:(我使用的pycharm windows版本)

nt means: this is a windows system.os.system("ipconfig") ##只是执行系统命令,但是没有返回结果

这样就可以打印出结果:result = os.popen("ipconfig").read()

print(result)

os.listdirprint(os.listdir()) ##当前目录都是有什么文件

输出:

['demon1.py', 'demon2.py', 'demon3.py', 'demon4.py', 'demon5.py', 'demon6.py', 'myapp.log', '__init__.py']

当然也可以跟参数:print(os.listdir("C:")) ##以列表的形式输出

输出:

['$GetCurrent', '$Recycle.Bin', 'Config.Msi', 'Dell', 'Documents and Settings', 'hiberfil.sys', 'inetpub', 'MSOCache', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'swapfile.sys', 'System Volume Information', 'unintall.log', 'Users', 'Windows']

进入某个目录,显示目录内的文件+子目录os.chdir("C:/ProgramData")

print(os.listdir())

输出:

['360zip', '9n8H4GJOzwU65y.VGC', 'Alibaba', 'alipay', 'Application Data', 'Baidu', 'Broadcom', 'c2eB74n.dat', 'D3UI6qHTv9.txt', 'Dell', 'Desktop', 'Documents', 'Downloaded Installations', 'dXh9T6r55r.RGy', 'EmTUi85b.i8D', 'Favorites', 'FH5rFSr1aZ8q98B', 'Git', 'Huorong', 'Intel', 'IyByJxuI3.xml', 'Jlcm', 'Kingsoft', 'KSafe', 'Ljqw51y.7k2', 'LSI', 'Microsoft', 'Microsoft Help', 'Microsoft OneDrive', 'Microsoft Toolkit', 'MSg21mVLt2.txt', 'MyDraw', 'nIRPpcU2W881bbS.3U5', 'NortonInstaller', 'NVIDIA', 'NVIDIA Corporation', 'Package Cache', 'PCDr', 'PPLive', 'regid.1991-06.com.microsoft', 'Roaming', 'SoftwareDistribution', 'Start Menu', 'SupportAssist', 'Templates', 'Tencent', 'Thunder Network', 'USOPrivate', 'USOShared', 'VMware', 'WindowsHolographicDevices']

os.getcwd ##类似linux下的pwdos.chdir("C:/ProgramData")

print(os.getcwd())

输出:

C:\ProgramData

os.mkdir(“test”) ##在当前目录,创建一个test目录

os.removedirs(“test”) ## 删除当前目录的test目录

os.remove(“myapp.log”) ## 删除当前目录下的文件(只针对文件)

os.rename(“demon1.py”, “demon11.py”) ## 把当前目录的demon1.py改为demon1.py

判断是否存在某个目录或文件os.chdir("C:/ProgramData") ## 切换到C:/ProgramData

if not os.path.exists("test"): ## 判断是否有test目录

os.mkdir("test") ##如果有:忽略,相反则创建一个test目录

显示当前目录的绝对路径print(os.path.abspath("./"))

输出:

D:\python\Python Items\Python_Test\9

sys 模块

提供了一系列有关Python运行环境的变量和函数

sys.argv命令行参数List,第一个元素是程序本身路径import sys

print(sys.argv[0]) 获取脚本名

print(sys.argv[1]) 获取第一个参数

print(sys.argv[2])

print(sys.argv[3])

先在pycharm里面配置好参数,我配置的($1 $2 $3 $4 $5)

输出:

D:/python/Python Items/Python_Test/9/demon7.py

s1

s2

s3

小事例:import sys

print("the script name is {0}".format(sys.argv[0]))

for i in sys.argv:

# print(i)

if i == sys.argv[0]:

continue

print("the para is {0}".format(i))

print("total the para is {0}".format(len(sys.argv)-1))

输出:

the script name is D:/python/Python Items/Python_Test/9/demon7.py

the para is s1

the para is s2

the para is s3

the para is s4

the para is s5

total the para is 5

sys.exit(n) 退出程序,正常退出时exit(0)>>> sys.exit()

sys.maxsize 最大的Int值>>> sys.maxsize

sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform 返回操作系统平台名称

sys.stdout 标准输出import sys

f = open('1.log','a') #以追加的模式打开一个文件

sys.stdout = f #指定标准输出到文件

print('hello python') #把输出stdout指定到了1.log

系统默认的输出:

__console__ = sys.stdout #默认console命令行

random 模块

random() 方法返回随机生成的一个实数,它在[0,1)范围内。import random

random.random()

注意:random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。

random.uniform(a,b)用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a

import random

print(random.uniform(1,10))

print(random.uniform(10,1))

random.randint(a, b)用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

import random

print(random.randint(1,10))

random.randrange([start], stop, [step])从指定范围内,按指定基数递增的集合中 获取一个随机数。

random.randrange(10, 30, 2),结果相当于从[10, 12, 14, 16, ... 26, 28]序列中获取一个随机数。random.randrange(10, 30, 2)在结果上与 random.choice(range(10, 30, 2) 等效。

import random

print(random.randrange(10,30,2))

random.choice(sequence)从序列中随机选取一个元素。seq需要是一个序列,比如list、元组、字符串。

import random

random.choice([1, 2, 3, 5, 8, 13]) #list

random.choice('hello') #字符串

random.choice(['hello', 'world']) #字符串组成的list

random.choice((1, 2, 3)) #元组

random.sample(sequence, k)从指定序列中随机获取指定长度的片断并随机排列。sample函数不会修改原有序列。

import random

lst = [1,2,3,4,5]

print(random.sample(lst,4))

print(lst)

练习:

随机列出几个数,随机100次 查看每个数字被随机出来的次数:import random

class NumberCount(object):

def __init__(self):

self.number1 = 0

self.number2 = 0

self.number3 = 0

self.number4 = 0

self.number5 = 0

self.number6 = 0

def count(self):

for i in range(1, 100):

number = random.randint(1, 6)

if number == 1:

self.number1 += 1

if number == 2:

self.number2 += 1

if number == 3:

self.number3 += 1

if number == 4:

self.number4 += 1

if number == 5:

self.number5 += 1

if number == 6:

self.number6 += 1

def result(self):

print("total the number of 1 appear {0} times".format(self.number1))

print("total the number of 2 appear {0} times".format(self.number2))

print("total the number of 3 appear {0} times".format(self.number3))

print("total the number of 4 appear {0} times".format(self.number4))

print("total the number of 5 appear {0} times".format(self.number5))

print("total the number of 6 appear {0} times".format(self.number6))

if __name__ == '__main__':

numberCount = NumberCount()

numberCount.count()

numberCount.result()

输出:

total the number of 1 appear 17 times

total the number of 2 appear 17 times

total the number of 3 appear 16 times

total the number of 4 appear 15 times

total the number of 5 appear 16 times

total the number of 6 appear 18 times

由此看来,几乎每个数字出现的次数几乎差不多!!!

string模块import string

print(string.ascii_letters) ##ascii_letters是生成所有字母,从a-z和A-Z

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.digits) ##生成所有数字0-9

0123456789

print(string.ascii_lowercase) ##全部的小写字母

abcdefghijklmnopqrstuvwxyz

print(string.ascii_uppercase) ##全部的大写字母

ABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.punctuation) ##全部的符号

!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~

print(string.hexdigits) ##数字+大小写abcdef

0123456789abcdefABCDEF

print(string.printable) ##打印出如上所有的数字+特殊字符+字母

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~

练习:

制作一个随机6位数的验证码(包含数字+字母)import string

import random

print("".join(random.sample(string.ascii_letters + string.digits, 6)))


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部