安裝python 的包
python 有很多的第三方軟件包, 提供了 標準庫中沒有的功能.
python 的官方支持的軟件包的網站: PyPI · The Python Package Index
在線安裝 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 的包
# 先下載 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 應用
# 安裝 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)
pip3 install 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': 沒有那個文件或目錄'
寫一個程序,測試此網絡內, 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 命令 可以遠程登錄一臺主機并遠程操作這臺主機
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脚本 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。