random 模块

>>> import random
>>> random.randint(1,6)  # random.randint(a,b) 生产 a~b的随机整数
3
>>> random.random()   # random.random  生成包含0但不包含1间浮点数
0.5884109388439075
>>> random.choice("ABCD")    # 从一个序列中,随机返回一个元素
'C'
>>> L = [1,2,3,6,9]
>>> random.choice(L)
6
>>> random.shuffle(L)   # random.shuffer(x)  # 把列表X 打乱
>>> L
[1, 6, 2, 9, 3]
写一个程序, 生产6位由数字组成的随机密码
import random
passwd = ''  # 要保存的字符串密码
for _ in range(6):
    ch = str(random.randint(0, 9))
    passwd += ch
print("密码是:", passwd)

m = random.random() * 1000000
print('密码是:%06d' % m )

time 模块

>>> import time
>>> time.time()   # 返回当前时间的时间戳
1617117219.0382686
>>> time.ctime()    #返回当前的UTC 时间的字符串
'Tue Mar 30 23:14:48 2021'
>>> t1 = time.localtime()   # 返回当前的本地时间元组
>>> t1
time.struct_time(tm_year=2021,tm_mon=3,tm_mday=30,tm_hour=23,tm_min=18,tm_sec=22,tm_wday=1,tm_yday=89,tm_isdst=0)
#struct_time 用 含有9个元素的元组来表示时间
>>> t1.tm_year
2021
>>> t1.tm_yday
89
>>> time.sleep(3)   # time.sleep(n)  # 让程序睡眠 n 秒
import time
for x in range(10):
    print(x)
    time.sleep(1)   # 让程序睡眠一秒
>>> time.strftime("%Y-%m-%d", t1)   # 格式化时间
'2021-03-30'
>>> time.strftime("%y-%m-%d", t1)			#更多用法查看官方文档
'21-03-30'
# 用时间元组来创建一个自定义的时间
>>> t2 = time.struct_time ( (2021,1, 1, 10, 11, 20, 0, 0, 0) )

OS 模块

对操作系统的访问大多使用 python 中的os 模块,同linux命令
文档: https://docs.python.org/zh-cn/3/library/os.html
>>> import os
>>> os.getcwd()  					# 返回当前的工作路径,pwd
'/root/桌面/py02/day03_code'
>>> os.mkdir('/tmp/nsd2012')   		# mkdir /tmp/nsd2012
>>> os.makedirs('/tmp/nsd2012/a/b/c')  # mkdir -p /tmp/nsd2012/a/b/c
>>> os.listdir()  # ls 
['mygames.py','idea']
>>> os.listdir('/tmp')  # ls /tmp  # 列出所有的文件夹
[ 'dir1', 'dir2']
>>> os.chdir('/tmp/nsd2012')  		# cd  /tmp/nsd2012
>>> os.getcwd()   					# pwd
>>> os.mknod('/tmp/myfile.txt')     # touch /tmp/myfile.txt
>>> os.chmod('/tmp/myfile.txt',0o755)  # chmod 755 /tmp/myfile.txt
>>> os.rmdir('/tmp/dir2')   		# rmdir /tmp/dir2  非空dir
>>> os.remove('/tmp/a.txt')  		# rm /tmp/a.txt
>>> os.rename('/tmp/myfile.txt','/tmp/a.txt')   # mv /tmp/myfile.txt /tmp/a.txt
>>> os.symlink('/etc/passwd', '/tmp/abc')  		# ln -s /etc/passwd /tmp/abc
2)字符串用于去掉空白字符串的方法 s.strip()
空白字符是指 ' '	 '\n' 	'\r'	 '\t'
>>> s = '    \n  \t hello world      \n'
>>> s.strip()      # 去掉左右两侧的空白字符
'hello world'
>>> s.lstrip()   # 去掉左侧的空白字符
'hello world      \n'
>>> s.rstrip()     # 去掉右侧的空白字符
'    \n  \t hello world'

OS.path 模块用于路径的操作的模块

>>> import os
>>> os.path.isabs('/root/abc.txt')   # 判断是否为绝对路径
True
>>> os.path.isdir('/tmp/nsd2012')    # 判断是否是文件夹
True
>>> os.mknod('/tmp/b.txt')   # touch /tmp/b.txt
>>> os.path.isfile('/tmp/b.txt')     # 判断是否是文件
True
>>> os.path.islink('/tmp/abc')      # 判断是否是软连接?
True
>>> os.path.ismount('/home')       # 存在并且是挂载点
True
>>> os.path.exists('/root')       # 判断文件或文件夹是否存在
True
>>> os.path.basename('/tmp/nsd2012/hello.py')  # 返回文件名
'hello.py'
>>> os.path.dirname('/tmp/nsd2012/hello.py')  # 返回路径
'/tmp/nsd2012'
>>> os.path.split('/tmp/nsd2012/hello.py')  # 拆分 路径和文件名
('/tmp/nsd2012', 'hello.py')
>>> os.path.join('/tmp/nsd2012', 'world.py')  # 拼接路径
'/tmp/nsd2012/world.py'

os.walk() 函数遍历文件夹

[root@localhost tmp]# tree /tmp/2012/
/tmp/2012/
├── a
│   ├── aaa.txt
│   └── b
│       ├── bbb.txt
│       └── c
└── aa
    └── bb
        └── cc
>>> for x in os.walk('/tmp/2012'):
...    print(x)
... 
#  (路径 , 路径内的所有文件夹列表 , 路径内的所有文件列表)
('/tmp/nsd2012', ['a', 'aa'], [])
('/tmp/nsd2012/a', ['b'], ['aaa.txt'])
('/tmp/nsd2012/a/b', ['c'], ['bbb.txt'])
('/tmp/nsd2012/a/b/c', [], [])
('/tmp/nsd2012/aa', ['bb'], [])
('/tmp/nsd2012/aa/bb', ['cc'], [])
('/tmp/nsd2012/aa/bb/cc', [], [])

shutil 模块

(shell util  工具)
文档: https://docs.python.org/zh-cn/3/library/shutil.html
>>> import shutil
>>> f1 = open('/etc/passwd', 'rb')
>>> f2 = open('/tmp/mypass.txt', 'wb')
>>> shutil.copyfileobj(f1, f2)
>>> f1.close()
>>> f2.close()
>>> 
>>> shutil.copy('/etc/passwd', '/tmp/mypass2.txt')    # cp /etc/passwd /tmp/mypass2.txt
'/tmp/mypass2.txt'
>>> shutil.copytree('/root/day_code', '/tmp/mycode')  # cp -r 
>>> shutil.move('/tmp/mypass.txt', '/tmp/nsd2012/a.txt')  # mv /tmp/mypass.txt /tmp/nsd2012/a.txt
>>> shutil.rmtree('/tmp/mycode')  		# rm -rf /tmp/mycode
>>> shutil.chown('/tmp/mypass.txt', user='xxx', group='yyy')  # 改属主属组

pymysql

import pymysql					#运行不报错,安装ok
# 连接数据库		##使用connect这个类
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    db='test1',   # 制定操作哪一个数据库
    charset='utf8'   # 制定操作的字符集
)

cursor = conn.cursor()  # 创建游标,操作数据库需要使用游标

# 制定要操作的 SQL 语句
create_dep = '''CREATE TABLE departments(id INT,dep_name VARCHAR (20),PRIMARY KEY(id))'''
# 使用游标 来执行 SQL 语句
cursor.execute(create_dep)  # 写入 SQL 语句
conn.commit()  # 提交SQL 语句到 服务器去执行
# 如果不再执行SQL 语句则 需要关闭游标
cursor.close()
# 操作完数据库,断开连接
conn.close()  # > quit;

执行完后的结果
[root@localhost ~]# mysql -uroot -ptedu.cn
MariaDB [(none)]> use test1;
MariaDB [nsd2012]> show tables;
MariaDB [nsd2012]> desc departments;
cursor = conn.cursor()  # 创建游标
# 在此处写SQL语句 进行增删改查操作
insert_sql = 'INSERT INTO departments VALUES (%s, %s)'
# 1. 插入数据
cursor.execute(insert_sql, (1, '人事部'))	# 插入一条数据到表 departments
conn.commit()  # 把SQL 语句提交到服务器
# 插入多行数据, 用 executemany 方法 第二个参数是 列表
# cursor.executemany(insert_sql, [
#     (2, '运维部'),
#     (3, '开发部'),
#     (4, '测试部'),
#     (5, '财务部'),
# ])
for x in range(10,100):			#批量插入
id=x
dep_name=”部门%d” %x
cursor.execute(insert_sql, (id,dep_name))	
# conn.commit()  # 把SQL 语句提交到服务器

# 2. 查询数数据
select_sql = 'SELECT id, dep_name FROM departments'
cursor.execute(select_sql)
#2.1 取出一行数据
result1 = cursor.fetchone()
print(result1)
#2.2 取出2行数据
result2 = cursor.fetchmany(2)
print(result2)
# 2.3 取出剩余的全部数据
result3 = cursor.fetchall()
print(result3)
# 3. 修改
update_sql = 'UPDATE departments SET dep_name=%s WHERE dep_name=%s'
cursor.execute(update_sql, ('人力资源部', '人事部'))
conn.commit()  # 提交
# 4. 删除
delete_sql = 'DELETE FROM departments WHERE id=%s'
r = cursor.execute(delete_sql, (5,))				#写成元组格式
conn.commit()
# 如果不再执行SQL 语句则 需要关闭游标
cursor.close()
# 操作完数据库,断开连接
conn.close()  # > quit;

subprocess 模块 用此模块可以执行系统命令

文档: https://docs.python.org/zh-cn/3/library/subprocess.html
- 示例
import subprocess
# shell=True, 指明此命令在 shell 环境下执行
# stdout=subprocess.PIPE 指明标准输入保存到 stdout属性中
result = subprocess.run('ls ~', shell=True, stdout=subprocess.PIPE)
print('刚才您输入的命令是:', result.args)   			#刚才您输入的命令是ls ~
print('此程序运行的返回值是:', result.returncode)   	#即 echo $?
print('此程序的标准输出是:', result.stdout.decode())  
# result.stdout绑定的是 ls ~ 打印在屏幕上的数据的字节串

# 执行一个命令,此命令会产生错误
r = subprocess.run('ls ~/abcdefg',     # ~/abcdefg 文件不存在
                   shell=True,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
print("ls ~/abcdefg 命令执行的返回值是:", r.returncode)  # 2
print("ls ~/abcdefg 命令执行的标准输出是:", r.stdout)   # b''
print("ls ~/abcdefg 命令执行的标准错误输出是:", r.stderr.decode())  # 'ls: 无法访问'/root/abcdefg': 没有那个文件或目录'

练习:写一个程序,测试此网络内,
# 192.168.1.1 ~  192.168.1.254 之间的机器,哪些开机,哪些关机
import subprocess
# r = subprocess.run('ping -c2 192.168.1.1 &> /dev/null', shell=True)
# if r.returncode == 0:
#     print('192.168.1.1 通')
# else:
#     print('192.168.1.1 不通')

def ping(host_ip):
    r = subprocess.run('ping -c2 %s &> /dev/null' % host_ip,
                       shell=True)
    if r.returncode == 0:
        print(host_ip, ': up')
    else:
        print(host_ip, ': down')
        
if __name__ == '__main__':
    # 生成 192.168.1.1 ~  192.168.1.254 范围内的IP
    for x in range(1, 255):
        ipv4 = '192.168.1.%d' % x
        # print("IP:", ipv4)
        ping(ipv4)			#传给def  ping(host_ip)

多线程编程

一个进程可以有多个执行路径,通常可以每个执行路径分配在不同的CPU 上并行执行, 这种运行方式是多线程。
文档:https://docs.python.org/zh-cn/3/library/threading.html

如何能让下面的两个函数同时执行 (目前输出完hellow才会输出world)

import time

def say_hello():
    for x in range(10):
        print("hello!!!")
        time.sleep(1)

def say_world():
    for y in range(10):
        print('world!!!')
        time.sleep(1)

say_hello()
say_world()

使用多线程 创建线程对象的方法

import threading
# 用threading 的 Thread 类来创建一个线程对象
threading.Thread(target=None, args=(), kwargs={}, *, daemon=None)
args  传参给target的None
import threading
import time

def say_hello():
    for x in range(10):
        print("hello!!!")
        time.sleep(1)

t = threading.Thread(target=say_hello) # 用threading 的 Thread 类来创建一个线程对象,用t变量绑定
t.start()   #用Thread对象的start()方法来启动线程,让 线程中target绑定的函数,异步执行
#输出hello!!!

完整示例

import threading  
import time
def say_hello():
    for x in range(10):
        print("hello!!!")
        time.sleep(1)
def say_world():
    for y in range(10):
        print('world!!!')
        time.sleep(1)

if __name__ == '__main__':	#自身导入模块name==main,导入的外面模块不执行???
    # 用多线程来并行
   
    t1 = threading.Thread(target=say_hello)   #创建一个线程,绑定say_hello函数
    t1.start()  # 启动 t1 线程
    t2 = threading.Thread(target=say_world)   #创建一个线程,绑定say_world函数
    t2.start()
print("主线程运行结束")

hello!!!			#输出结果
world!!!
主线程运行结束
hello!!!
world!!!
...

练习多网络测试

import subprocess
import threading

def ping(host_ip):
    r = subprocess.run('ping -c2 %s &> /dev/null' % host_ip,shell=True)
    if r.returncode == 0:
        print(host_ip,': up')
    else:
        print(host_ip,': down')
if __name__ == '__main__':
    # 生成 192.168.1.1 ~  192.168.1.254 范围内的IP
    for x in range(1,255):
        ipv4 = '192.168.1.%d' % x
        # print("IP:", ipv4)
        # 创建一个线程,执行ping 函数
        t = threading.Thread(target=ping, args=(ipv4,))		#元组传参,多线程同时处理
        t.start()
        # ping(ipv4)

paramiko 模块 实现 ssh

pip3 install paramiko   #安装 paramiko

import paramiko
ssh_clint = paramiko.SSHClient()  # 创建一个paramko 客户端对象
ssh_clint.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 设置自动接受服务器的主机密钥

# 登陆远程主机
ssh_clint.connect('192.168.1.11',   # 远程主机的IP
                  username='root',  # 远程主机的用户名
                  password='root',  # 远程主机的密码
                  port=22  # ssh 的端口号
                  )

# 在此处操作远程主机
result = ssh_clint.exec_command('id root; id tom')   # 在远程主机上执行命令
# print('len(result)=', len(result))  # result 绑定三个文件流对象的元组

stdout = result[1]   # 得到标准输出
stderr = result[2]   # 得到标准错误输出
print("标准输出:", stdout.read().decode())
print("标准错误输出:", stderr.read().decode())

ssh_clint.exec_command('mkdir test')  #创建目录
ssh_clint.close()  # 相当于在ssh 的内部执行  exit 命令

requests 模块

发送HTTP 协议的请求,得到服务器响应的数据模拟浏览器的行为
安装方法:pip3 install requests
HTTP 协议的请求方式:
1、GET 请求相当于查看 ,get请求可以获取网站的数据,请求参数通常跟在URL 的后面
2、POST请求原意是创建或者添加, post请求通常用于注册、提交表单或上传文件等

示例使用request模块获取网页数据
>>> import requests
>>> r = requests.get('https://www.baidu.com')  #发送GET请求得到响应
>>> r.text  # 得到响应内容的文本信息
'<html>...</html>'

使用request模块下载文件
>>> import requests
>>> r = requests.get('http://photo.qc188.com/upload/20197/31/24820/df32.jpg')
>>> r.content  # 响应的字节串
# 下载图片
>>> r = requests.get('http://photo.qc188.com/upload/20197/31/24820/df3.jpg')
>>> 
>>> with open('benz.jpg', 'wb') as fw:
...      fw.write(r.content)  # 将响应的内容(bytes) 写入文件
... 

用request模块获取 中国天气网的json 数据
>>> import requests
>>> url = 'http://www.weather.com.cn/data/sk/101010100.html'
>>> r = requests.get(url)
>>> r.content  # 返回字节串
b'{"weatherinfo":..."}}'
>>> r.json()  # 将字节串,转化为python 的对象,相当于 json.loads(r.content.decode())
{'w...}}
>>> r.encoding  # 查看当前的字符编码
'ISO-8859-1'
>>> r.encoding = 'utf8' # 将编码改为 UTF-8
>>> r.json()
{'...'}}

requests.get ()为连接添加查询字符串使用params 字典完成
import requests
import requests
url = 'https://www.sogou.com/web'
# https://www.sogou.com/web?query=linux
s = input('请输入查询的内容:')
params = {'query': s}
r = requests.get(url, params=params)  # 发出get请求,传入 ?query=s 查询字符串
    # 相当于请求:https://www.sogou.com/web?query=linux
with open('sogou_' + s + '.html', 'wb') as fw:
    fw.write(r.content)   # 把 r.content 字节串写入文件
# https://www.sogou.com/web?query=linux
s = input('请输入查询的内容:')
params = {'query': s}
r = requests.get(url, params=params)  # 发出get请求,传入 ?query=s 查询字符串
    # 相当于请求:https://www.sogou.com/web?query=linux
with open('sogou_' + s + '.html', 'wb') as fw:
    fw.write(r.content)   # 把 r.content 字节串写入文件
request 可以通过 headers 传递请求头
url = 'https://www.sogou.com/web'
params = {'query': 'linux'}
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
}   # 带上 'User-Agent' 请求头,把自己伪装成浏览器爬虫,抢票,查找请求头如下图
r = requests.get(url, params=params, headers=headers)
r.text  # 返回网页的内容

完整代码:
import requests

url = 'https://www.sogou.com/web'
# https://www.sogou.com/web?query=linux    等同于搜索框里输入linux
s = input('请输入查询的内容:')
params = {'query': s}
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
}   # 带上 'User-Agent' 请求头,把自己伪装成浏览者

r = requests.get(url, params=params, headers=headers)  # 发出get请求,传入 ?query=s 查询字符串
    # 相当于请求:https://www.sogou.com/web?query=linux
with open('sogou_' + s + '.html', 'wb') as fw:
    fw.write(r.content)   # 把 r.content 字节串写入文件

split用法

输入一行,结果输出一个整数,表示输入字符串最后一个单词的长度
输入:hello nowcoder
输出: 8

a = input()
list1=a.split()
sum1=len(list1[-1])
print(sum1)
u = "www.doiido.com.cn"
print (u.split())            #['www.doiido.com.cn']
print (u.split('.'))          #['www', 'doiido', 'com', 'cn']
print (u.split('.',1))        #['www', 'doiido.com.cn']
print (u.split('.',2))        #['www', 'doiido', 'com.cn']
print (u.split('.',2)[1])        #doiido
print (u.split('.',-1))        #['www', 'doiido', 'com', 'cn']
u1,u2,u3 = u.split('.',2)
print(u1)          #www

str="hello boy<[www.doiido.com]>byebye"
print(str.split("[")[1].split("]")[0])		#www.doiido.com
print(str.split("[")[1].split("]")[0].split("."))	#['www', 'doiido', 'com']

lower()函数 将字符串中的所有大写字母转换为小写字母,upper()转大写

第一行输入一个由字母和数字以及空格组成的字符串,第二行输入一个字符。
输出描述:输出输入字符串中含有该字符的个数。(不区分大小写字母)

输入:ABCabc   A
a= input().lower()
b=input().lower()
print(a.count(b))    a有两个
第一行先输入随机整数的个数N。接下来的N行每行输入一个整数,输出
输入:
3  
2
2
1
输出  
1 
2

n = int(input())
list = []
for i in range(n):
    a = int(input())
    if a not in list:
        list.append(a)
        list.sort()
for i in list:
    print(i)

ljust()方法语法:返回一个原字符串左对齐,并使用空格填充至指定长度

•输入一个字符串,请按长度为8拆分每个输入字符串并进行输出;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

a = input()
b=len(a)%8
if b >0:
    c=a[len(a)-b::]
    print(c.ljust(8,"0"))
else:
    print(a[len(a)-8::])

int(数字,进制) 进制转换

print(int(input(), 16))
输入:0xAA   输出:170

print(int(input(), 2))
输入:111111  输出:63 

math模块

指数、对数、平方根、三角函数等运算。

import math
line = int(input())
i = 2
n = math.sqrt(line)
while i <= n and line > 1:
    if line % i == 0: 
        print(i, end=' ')
        line /= i
        continue
    i += 1
if line != 1: print(int(line))
import math 
a = math.sqrt(16)     
b = math.sqrt(10)
print(a)    4.0
print(b)    3.1622776601683795
sqrt开方、pow幂数、log底数、sin cos正弦余弦...

round函数

round(number,num_digits)  number:需要四舍五入的数  digits:需要小数点后保留的位数;
s = 1.234567
print(round(s, 2))
1.23
Logo

一站式 AI 云服务平台

更多推荐