属性、正则表达式、pymysql、多线程编程

2021-07-26  本文已影响0人  秋天丢了李姑娘

昨天回顾

属性

class A:
    def say_hello(self):
        print('Hello A')

class B(A):
    def say_hello(self):
        print("hello B")
       # self.say_hello() 无限递归调用
       # 能否在此方法内调用 A类里面的 say_hello()
       # 方法1
       # A.say_hello(self)
       # 方法2  ,super() 会把self 看成是A类的对象
        super().say_hello()

b = B()
b.say_hello()  # hello B    Hello A 

正则表达式 (regular express)

正则表达式是表示 文字的排列规则的一个字符串, 使用来匹配文字的匹配模式.

元字符

类别 元字符
匹配字符 .(不包含\n) [...] [^...] \d \D \w \W \s \S
匹配重复 * + ? {n} {m,n}
匹配位置 ^ $ \b \B
其他 `

安装python 的包

python 有很多的第三方软件包, 提供了 标准库中没有的功能.

python 的官方支持的软件包的网站: https://pypi.org

在Redhat 或 cent OS 上 yum 用于安装 rpm 包

Python 使用 pip3 命令(Windows 上用pip命令) 来安装 Python 的包

在线安装 python 的包

打开一个终端

pip3 install 包名

离线安装 python 的包

# 先下载 XlsxWriter-1.3.8-py2.py3-none-any.whl
pip3 install XlsxWriter-1.3.8-py2.py3-none-any.whl
pip3 install pymysql........whl

# 先下载 XlsxWriter-1.3.8.tar.gz 压缩文件格式的包
tar -xzvf XlsxWriter-1.3.8.tar.gz
cd XlsxWriter-1.3.8 # 进入解压缩后的文件夹
python3 setup.py install # 用 python3 运行setup.py 来安装

pymysql 应用

创建一个 nsd21xx 的数据库

MariaDB [(none)]> CREATE DATABASE nsd21xx DEFAULT CHARSET utf8;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| nsd21xx            |
| performance_schema |
+--------------------+
4 rows in set (0.000 sec)

pip3 install pymysql

用 pymysql 模块来操作数据库

见: pymysql_create_table.py

file: pymysql_create_table.py

# 导入 pymysql 包
import pymysql

# 连接数据库

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='tedu.cn',
    db='nsd21xx',   # 指定操作哪一个数据库
    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
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.3.27-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use nsd21xx;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

MariaDB [nsd21xx]> show tables;
Empty set (0.000 sec)

MariaDB [nsd21xx]> show tables;
+-------------------+
| Tables_in_nsd21xx |
+-------------------+
| departments       |
+-------------------+
1 row in set (0.000 sec)

MariaDB [nsd21xx]> desc departments;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   | PRI | NULL    |       |
| dep_name | varchar(20) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.001 sec)

此示例示意 数据库的增删改查操

file: pymysql_create_table.py

1. 增加数据

# 导入 pymysql 包
import pymysql

# 连接数据库

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='tedu.cn',  # 密码以实际情况为主
    db='nsd21xx',   # 指定操作哪一个数据库
    charset='utf8'   # 指定操作的字符集
)

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

# 在此处写SQL语句 进行增删改查操作
# 1\. 插入数据
insert_sql = 'INSERT INTO departments VALUES (%s, %s)'
# # 1.1 插入一条数据到表 departments
cursor.execute(insert_sql, (1, '人事部'))
# # 1.2 插入多行数据, 用 executemany 方法 第二个参数是 列表
cursor.executemany(insert_sql, [
     (2, '运维部'),
     (3, '开发部'),
     (4, '测试部'),
     (5, '财务部'),
])
conn.commit()  # 把SQL 语句提交到服务器

2. 查询数据

# 导入 pymysql 包
import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='tedu.cn',    # 密码
    db='nsd21xx',   # 指定操作哪一个数据库
    charset='utf8'   # 指定操作的字符集
)

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

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. 修改数据

# 导入 pymysql 包
import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='tedu.cn',    # 密码
    db='nsd21xx',   # 指定操作哪一个数据库
    charset='utf8'   # 指定操作的字符集
)

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

update_sql = 'UPDATE departments SET dep_name=%s WHERE dep_name=%s'
cursor.execute(update_sql, ('人力资源部', '人事部'))
conn.commit()  # 提交

4. 删除数据

# 导入 pymysql 包
import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='tedu.cn',    # 密码
    db='nsd21xx',   # 指定操作哪一个数据库
    charset='utf8'   # 指定操作的字符集
)

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

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

答案

# 写一个程序,测试此网络内,
# 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)

多线程编程

一个进程可以有多个执行路径,通常可以每个执行路径分配在不同的CPU 上并行执行, 这种运行方式是多线程

文档:https://docs.python.org/zh-cn/3/library/threading.html

如何能让下面的两个函数同时执行

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)

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__':
    # 用多线程来并行
    # 1\. 创建一个线程,绑定 say_hello 函数
    t1 = threading.Thread(target=say_hello)
    t1.start()  # 启动 t1 线程
    t2 = threading.Thread(target=say_world)
    t2.start()

print("主线程运行结束")

 # 串行
 # say_hello()
 # say_world()

paramiko 模块

此模块实现了 ssh 客户端的功能

ssh 命令 可以远程登录一台主机并远程操作这台主机

pip3 install paramiko

# 导入 paramiko 模块
import paramiko

# 创建一个paramko 客户端对象
ssh_clint = paramiko.SSHClient()

# 设置自动接受服务器的主机密钥
ssh_clint.set_missing_host_key_policy(paramiko.AutoAddPolicy())

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

# 在此处操作远程主机
result = ssh_clint.exec_command('id root; id zhangsan')   # 在远程主机上执行命令
# 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 魏老师的专用文件夹')

# 关闭连接
ssh_clint.close()  # 相当于在ssh 的内部执行  exit 命令
上一篇 下一篇

猜你喜欢

热点阅读