日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

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

發(fā)布時間:2025/3/21 数据库 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 安装python 的包控制mysql的Python脚本与执行系统命令的Python脚本 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

安裝python 的包

python 有很多的第三方軟件包, 提供了 標(biāo)準(zhǔn)庫中沒有的功能.

python 的官方支持的軟件包的網(wǎng)站: 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
  • 更換國內(nèi)的pip 源

    # 在用戶主目錄下創(chuàng)建一個文件夾 .pip mkdir ~/.pip # 在 ~/.pip/文件夾下創(chuàng)建一個文件 'pip.conf' vim ~/.pip/pip.conf # 寫入如下內(nèi)容 [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 # 進(jìn)入解壓縮后的文件夾 python3 setup.py install # 用 python3 運(yùn)行setup.py 來安裝

pymysql 應(yīng)用

  • 安裝 mysql-server 或 mariadb-server

# 安裝 mariadb yum install mariadb-server # 啟動 mariadb 服務(wù) systemctl start mariadb # systemctl restart mariadb systemctl enable maridb # 修改管理員賬號的密碼為 tedu.cn mysqladmin password tedu.cn # 用 mysql 客戶端來登錄數(shù)據(jù)庫 mysql -uroot -ptedu.cn ? # 創(chuàng)建一個 nsd21xx 的數(shù)據(jù)庫 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 模塊來操作數(shù)據(jù)庫

  • 用 pymysql 創(chuàng)建數(shù)據(jù)表

  • 源代碼

# file: pymysql_create_table.py ? # 導(dǎo)入 pymysql 包 import pymysql ? # 連接數(shù)據(jù)庫 ? conn = pymysql.connect(host='localhost',user='root',password='tedu.cn',db='nsd21xx', # 指定操作哪一個數(shù)據(jù)庫charset='utf8' # 指定操作的字符集 ) ? # 操作數(shù)據(jù)庫 # 需要使用 游標(biāo)來操作數(shù)據(jù)庫 cursor = conn.cursor() # 創(chuàng)建游標(biāo) ? # 制定要操作的 SQL 語句 create_dep = '''CREATE TABLE departments( id INT, dep_name VARCHAR (20), PRIMARY KEY(id) )''' ? # 使用游標(biāo) 來執(zhí)行 SQL 語句 cursor.execute(create_dep) # 寫入 SQL 語句 conn.commit() # 提交SQL 語句到 服務(wù)器去執(zhí)行 ? # 如果不再執(zhí)行SQL 語句則 需要關(guān)閉游標(biāo) cursor.close() ? # 操作完數(shù)據(jù)庫,斷開連接 conn.close() # > quit;

?結(jié)果

[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 模塊實(shí)現(xiàn)對 mysql數(shù)據(jù)庫的增刪改查

# 此示例示意 數(shù)據(jù)庫的增刪改查操 ? ? # file: pymysql_create_table.py ? # 導(dǎo)入 pymysql 包 import pymysql ?# 連接數(shù)據(jù)庫 ? conn = pymysql.connect(host='localhost',user='root',password='tedu.cn',db='nsd21xx', # 指定操作哪一個數(shù)據(jù)庫charset='utf8' # 指定操作的字符集 ) ? # 操作數(shù)據(jù)庫 # 需要使用 游標(biāo)來操作數(shù)據(jù)庫 cursor = conn.cursor() # 創(chuàng)建游標(biāo) ? # 在此處寫SQL語句 進(jìn)行增刪改查操作 # 1. 插入數(shù)據(jù) # insert_sql = 'INSERT INTO departments VALUES (%s, %s)' # # 1.1 插入一條數(shù)據(jù)到表 departments # cursor.execute(insert_sql, (1, '人事部')) # # 1.2 插入多行數(shù)據(jù), 用 executemany 方法 第二個參數(shù)是 列表 # cursor.executemany(insert_sql, [ # (2, '運(yùn)維部'), # (3, '開發(fā)部'), # (4, '測試部'), # (5, '財(cái)務(wù)部'), # ]) # conn.commit() # 把SQL 語句提交到服務(wù)器 ? # 2. 查詢數(shù)數(shù)據(jù) select_sql = 'SELECT id, dep_name FROM departments' cursor.execute(select_sql) #2.1 取出一行數(shù)據(jù) result1 = cursor.fetchone() print(result1) #2.2 取出2行數(shù)據(jù) result2 = cursor.fetchmany(2) print(result2) # 2.3 取出剩余的全部數(shù)據(jù) 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() ? # 如果不再執(zhí)行SQL 語句則 需要關(guān)閉游標(biāo) cursor.close() ? # 操作完數(shù)據(jù)庫,斷開連接 conn.close() # > quit;

subprocess 模塊

用此模塊可以執(zhí)行系統(tǒng)命令

文檔: subprocess --- 子進(jìn)程管理 — Python 3.9.7 文檔

  • 示例

import subprocess# shell=True, 指明此命令在 shell 環(huán)境下執(zhí)行 # stdout=subprocess.PIPE 指明標(biāo)準(zhǔn)輸出保存到 stdout 屬性中 result = subprocess.run('ls ~', shell=True, stdout=subprocess.PIPE) print('剛才您輸入的命令是:', result.args) # 執(zhí)行的命令 'ls ~' print('此程序運(yùn)行的返回值是:', result.returncode# 寫一個程序,測試此網(wǎng)絡(luò)內(nèi), # 192.168.1.1 ~ 192.168.1.254 之間的機(jī)器, # 哪些開機(jī),哪些關(guān)機(jī) ? 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 范圍內(nèi)的IPfor x in range(1, 255):ipv4 = '192.168.1.%d' % x# print("IP:", ipv4)ping(ipv4)) # 即 $?# result.stdout綁定的是 ls ~ 打印在屏幕上的數(shù)據(jù)的字節(jié)串 print('此程序的標(biāo)準(zhǔn)輸出是:', result.stdout.decode())# 執(zhí)行一個命令,此命令會產(chǎn)生錯誤 r = subprocess.run('ls ~/abcdefg', # ~/abcdefg 文件不存在shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) print("ls ~/abcdefg 命令執(zhí)行的返回值是:", r.returncode) # 2 print("ls ~/abcdefg 命令執(zhí)行的標(biāo)準(zhǔn)輸出是:", r.stdout) # b'' print("ls ~/abcdefg 命令執(zhí)行的標(biāo)準(zhǔn)錯誤輸出是:", r.stderr.decode()) # 'ls: 無法訪問'/root/abcdefg': 沒有那個文件或目錄'
  • 示例2

寫一個程序,測試此網(wǎng)絡(luò)內(nèi),
192.168.1.1 ~ ?192.168.1.254 之間的機(jī)器,哪些開機(jī),哪些關(guān)機(jī)
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 不通')

# 寫一個程序,測試此網(wǎng)絡(luò)內(nèi), # 192.168.1.1 ~ 192.168.1.254 之間的機(jī)器, # 哪些開機(jī),哪些關(guān)機(jī) ? 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 范圍內(nèi)的IPfor x in range(1, 255):ipv4 = '192.168.1.%d' % x# print("IP:", ipv4)ping(ipv4)

paramiko 模塊

此模塊實(shí)現(xiàn)了 ssh 客戶端的功能

ssh 命令 可以遠(yuǎn)程登錄一臺主機(jī)并遠(yuǎn)程操作這臺主機(jī)

  • 安裝 paramiko

pip3 install paramiko
  • 示例

# 導(dǎo)入 paramiko 模塊 import paramiko ? # 創(chuàng)建一個paramko 客戶端對象 ssh_clint = paramiko.SSHClient() ? # 設(shè)置自動接受服務(wù)器的主機(jī)密鑰 ssh_clint.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ? # 登陸遠(yuǎn)程主機(jī) ssh_clint.connect('192.168.1.64', # 遠(yuǎn)程主機(jī)的IPusername='root', # 遠(yuǎn)程主機(jī)的用戶名password='root', # 遠(yuǎn)程主機(jī)的密碼port=22 # ssh 的端口號) ? # 在此處操作遠(yuǎn)程主機(jī) result = ssh_clint.exec_command('id root; id zhangsan') # 在遠(yuǎn)程主機(jī)上執(zhí)行命令 # print('len(result)=', len(result)) # result 綁定三個文件流對象的元組 ? stdout = result[1] # 得到標(biāo)準(zhǔn)輸出 stderr = result[2] # 得到標(biāo)準(zhǔn)錯誤輸出 print("標(biāo)準(zhǔn)輸出:", stdout.read().decode()) print("標(biāo)準(zhǔn)錯誤輸出:", stderr.read().decode()) ? ssh_clint.exec_command('mkdir 專用文件夾') ? # 關(guān)閉連接 ssh_clint.close() # 相當(dāng)于在ssh 的內(nèi)部執(zhí)行 exit 命令

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的安装python 的包控制mysql的Python脚本与执行系统命令的Python脚本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。