欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

安装python 的包控制mysql的Python脚本与执行系统命令的Python脚本

发布时间:2025/3/21 数据库 26 豆豆
生活随笔 收集整理的这篇文章主要介绍了 安装python 的包控制mysql的Python脚本与执行系统命令的Python脚本 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

安装python 的包

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

python 的官方支持的软件包的网站: PyPI · The Python Package Index

  • 安装方法

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

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

在线安装 python 的包

  • 打开一个终端
pip3 install 包名
  • 示例

pip3 install wget # 或者 pip3 install pymysql
  • 解决错误的方法

  • 更新 pip3

  • pip3 install --upgrade pip # 或者 python3 -m pip install -U pip
  • 更换国内的pip 源

    # 在用户主目录下创建一个文件夹 .pip mkdir ~/.pip # 在 ~/.pip/文件夹下创建一个文件 'pip.conf' vim ~/.pip/pip.conf # 写入如下内容 [global] index-url=http://mirrors.aliyun.com/pypi/simple/ [install] trusted-host=mirrors.aliyun.com

    也可以百度搜寻其他的源

  • 在使用 pip3 命令时手动指定源

    pip3 install -i 源的地址 模块名

    示例

    pip3 install -i http://mirrors.aliyun.com/pypi/simple/ wget pip3 install -i http://mirrors.aliyun.com/pypi/simple/ pymysql

离线安装 python 的包

  • 方式一 : 安装 .whl 的包

# 先下载 XlsxWriter-1.3.8-py2.py3-none-any.whl pip3 install XlsxWriter-1.3.8-py2.py3-none-any.whl pip3 install pymysql........whl
  • 方式二: 安装压缩包类型的python 包

# 先下载 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 应用

  • 安装 mysql-server 或 mariadb-server

# 安装 mariadb yum install mariadb-server # 启动 mariadb 服务 systemctl start mariadb # systemctl restart mariadb systemctl enable maridb # 修改管理员账号的密码为 tedu.cn mysqladmin password tedu.cn # 用 mysql 客户端来登录数据库 mysql -uroot -ptedu.cn ​ # 创建一个 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)
  • 安装 pymysql 包

pip3 install pymysql

用 pymysql 模块来操作数据库

  • 用 pymysql 创建数据表

  • 源代码

# 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) ​
  • 用pymysql 模块实现对 mysql数据库的增删改查

# 此示例示意 数据库的增删改查操 ​ ​ # 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语句 进行增删改查操作 # 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. 查询数数据 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 模块

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

文档: subprocess --- 子进程管理 — Python 3.9.7 文档

  • 示例

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# 写一个程序,测试此网络内, # 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 范围内的IPfor x in range(1, 255):ipv4 = '192.168.1.%d' % x# print("IP:", ipv4)ping(ipv4)) # 即 $?# result.stdout绑定的是 ls ~ 打印在屏幕上的数据的字节串 print('此程序的标准输出是:', result.stdout.decode())# 执行一个命令,此命令会产生错误 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': 没有那个文件或目录'
  • 示例2

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

# 写一个程序,测试此网络内, # 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 范围内的IPfor x in range(1, 255):ipv4 = '192.168.1.%d' % x# print("IP:", ipv4)ping(ipv4)

paramiko 模块

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

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

  • 安装 paramiko

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', # 远程主机的IPusername='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 命令

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的安装python 的包控制mysql的Python脚本与执行系统命令的Python脚本的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。