2025年Pytorch-gpu版本安裝(各種情況適用自己的安裝需求,親測絕對有效,示例安裝torch2.6.0,過程詳細面向小白)_torch gpu版本-CSDN博客
https://blog.csdn.net/OpenSeek/article/details/145795127
2.2 查錯
import sys
import MySQLdb
try:conn = MySQLdb.connect (db = "cookbook",host = "localhost",user = "cbuser", passwd = "cbpass")print ("Connected")
except MySQLdb.Error as e:print ("Cannot connect to server")print ("Error code:", e.args[0])print ("Error message:", e.args[1])sys.exit(1)conn.close()
print ("Disconnected")
import sys
import MySQLdbtry:conn = MySQLdb.connect(db="cookbook",host="localhost",user="cbuser",passwd="cbpass")print("Connected")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()
print("Disconnected")
以下是你的 Python 腳本的逐行分析及常見問題解決方案:
代碼功能
嘗試連接 MySQL 數據庫 cookbook,若成功則關閉連接,若失敗則輸出錯誤信息。
常見錯誤及解決方案
1. MySQL 服務未啟動
? 現象:拋出 Can't connect to MySQL server on 'localhost' 錯誤。
? 解決:
o Windows:打開服務管理器(services.msc),啟動 MySQL 服務。
o Linux/macOS:運行 sudo systemctl start mysql。
2. 數據庫憑證錯誤
? 現象:拋出 Access denied for user 'cbuser'@'localhost' 錯誤。
? 解決:
1. 確認數據庫名、用戶名、密碼是否正確。
2. 使用命令行測試連接:
bash
復制
mysql -u cbuser -p cbpass cookbook
3. 如果密碼錯誤,重置密碼:
sql
復制
ALTER USER 'cbuser'@'localhost' IDENTIFIED BY 'new_password';
3. 用戶權限不足
? 現象:拋出 Host 'localhost' is not allowed to connect 錯誤。
? 解決:授予用戶權限:
sql
復制
GRANT ALL PRIVILEGES ON cookbook.* TO 'cbuser'@'localhost' IDENTIFIED BY 'cbpass';
FLUSH PRIVILEGES;
4. MySQLdb 庫未正確安裝
? 現象:拋出 ModuleNotFoundError: No module named 'MySQLdb'。
? 解決:
o Python 3:安裝 mysqlclient:
bash
復制
pip install mysqlclient
o Windows:需安裝 MySQL Connector/C 并確保環境變量包含 libmysql.dll。
5. 連接參數錯誤
? 現象:拋出 Unknown MySQL server host 或 Can't connect to local MySQL server。
? 解決:
o 檢查 host 是否為 localhost 或 127.0.0.1。
o 指定端口(默認 3306):
python
復制
conn = MySQLdb.connect(db="cookbook",host="localhost",port=3306,user="cbuser",passwd="cbpass"
)
調試建議
1. 打印完整錯誤信息:修改異常捕獲代碼,輸出詳細錯誤:
python
復制
except MySQLdb.Error as e:print(f"Error {e.args[0]}: {e.args[1]}")
2. 手動測試連接:用命令行工具驗證數據庫是否可達:
bash
復制
mysql -h localhost -u cbuser -p cbpass cookbook
3. 檢查防火墻:確保本地防火墻未阻止 MySQL 端口(默認 3306)。
________________________________________
修正后的代碼
python
復制
import sys
import MySQLdbtry:conn = MySQLdb.connect(db="cookbook",host="localhost",user="cbuser",passwd="cbpass")print("Connected")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()print("Disconnected")
________________________________________
關鍵檢查點
問題類型 檢查方法
MySQL 服務狀態 sudo systemctl status mysql
用戶權限 SHOW GRANTS FOR 'cbuser'@'localhost';
密碼正確性 mysql -u cbuser -p
Python 庫安裝 pip show mysqlclient
從你的 pip3 show torch 輸出可以看出,當前安裝的 PyTorch 版本為 1.13.1+cpu,而 Hugging Face Transformers 庫要求 PyTorch ≥ 2.6。以下是針對 Windows 系統和 Conda 環境的完整解決方案:
1. 升級 PyTorch 到 2.6+
步驟 1:卸載舊版本 PyTorch
在終端中運行以下命令(以管理員身份運行):pip uninstall torch torchvision torchaudio -y
步驟 2:通過 Conda 安裝 PyTorch 2.6+(CPU 版本)
由于你使用的是 Conda 環境,建議通過 Conda 安裝以解決依賴沖突:conda activate myenv # 激活你的 Conda 環境(如 base)
conda install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
(無法安裝!!!!)
1. 更換國內鏡像源加速
步驟 1:配置清華鏡像源
在終端中運行以下命令:conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --set show_channel_urls yes
步驟 2:清除緩存
conda clean -i
2. 使用 Mamba 加速依賴解析
Mamba 是 Conda 的替代工具,依賴解析速度更快:步驟 1:安裝 Mamba
conda install -n base -c conda-forge mamba
步驟 2:通過 Mamba 安裝 PyTorch
mamba install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
3. 創建干凈的 Conda 環境
如果現有環境存在依賴沖突,新建一個環境:conda create -n pytorch26 python=3.10
conda activate pytorch26
conda install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
4. 分步安裝依賴(備用方案)
如果自動安裝失敗,手動指定依賴版本:conda install numpy=1.24.3 typing-extensions=4.7.1
conda install pytorch=2.6 torchvision=0.17.0 torchaudio=2.0.0 cpuonly -c pytorch
5. 驗證安裝
安裝完成后運行以下命令:python -c "import torch; print(torch.__version__)" # 應輸出 2.6.0+C:\Users\lenovo>pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
Successfully installed torch-1.13.1+cpu torchaudio-0.13.1+cpu torchvision-0.14.1+cpu
2.3 編寫庫文件如何將公共操作代碼放入庫文件中。假設不想將庫文件被語言處理器默認搜索的目錄是放在windows 下使用c:\lib\mcb
%run c:/lib/mcb/connect.pyConnected
Disconnected
封裝(或模塊化)并不是一個“解決文案”而是一項編程技術。不用再在每個程序里重復編寫相同的代碼。僅調用庫中的一個行程序,程序都可以在recipes發行包的lib 目錄下找到。
通過調用庫里面的程序編寫連接到數據庫的程序,只需要做出變化的位置局部化:僅需要修改受影響的庫程序。
代碼封裝提升安全性。
庫文件自身并不能獨立使用,都是通過一個簡短的“test harness”程序來說明的。拷貝一份文件在connect 和disconnect 調用之間加入你自己的代碼。
Cell 1: Run the script using %run
%run c:/lib/mcb/Cookbook.py
#! c:/lib/mcb/Cookbook.py
Cell 2: Use the loaded function
import sys
import MySQLdbtry:conn = connect()print("Connected to database")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()print("Disconnected")
Connected to database
Disconnected
2.4 發起語句并檢索結果
mysql> select * from profile;
+----+---------+------------+-------+-----------------------+------+
| id | name | birth | color | foods | cats |
+----+---------+------------+-------+-----------------------+------+
| 1 | Fred | 1970-04-13 | black | lutefisk,fadge,pizza | 0 |
| 2 | Mort | 1969-09-30 | white | burrito,curry,eggroll | 3 |
| 3 | Brit | 1957-12-01 | red | burrito,curry,pizza | 1 |
| 4 | Carl | 1973-11-02 | red | eggroll,pizza | 4 |
| 5 | Sean | 1963-07-04 | blue | burrito,curry | 5 |
| 6 | Alan | 1965-02-14 | red | curry,fadge | 1 |
| 7 | Mara | 1968-09-17 | green | lutefisk,fadge | 1 |
| 8 | Shepard | 1975-09-02 | black | curry,pizza | 2 |
| 9 | Dick | 1952-08-20 | green | lutefisk,fadge | 0 |
| 10 | Tony | 1960-05-01 | white | burrito,pizza | 0 |
| 11 | Alison | 1973-01-12 | blue | eggroll | 4 |
| 12 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 13 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 14 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 15 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 16 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 17 | Amabel | NULL | NULL | NULL | NULL |
+----+---------+------------+-------+-----------------------+------+
17 rows in set (0.01 sec)
mysql> update profile set cats = cats + 1 where name = 'Fred'-> ;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from profile;
+----+---------+------------+-------+-----------------------+------+
| id | name | birth | color | foods | cats |
+----+---------+------------+-------+-----------------------+------+
| 1 | Fred | 1970-04-13 | black | lutefisk,fadge,pizza | 1 |
| 2 | Mort | 1969-09-30 | white | burrito,curry,eggroll | 3 |
| 3 | Brit | 1957-12-01 | red | burrito,curry,pizza | 1 |
| 4 | Carl | 1973-11-02 | red | eggroll,pizza | 4 |
| 5 | Sean | 1963-07-04 | blue | burrito,curry | 5 |
| 6 | Alan | 1965-02-14 | red | curry,fadge | 1 |
| 7 | Mara | 1968-09-17 | green | lutefisk,fadge | 1 |
| 8 | Shepard | 1975-09-02 | black | curry,pizza | 2 |
| 9 | Dick | 1952-08-20 | green | lutefisk,fadge | 0 |
| 10 | Tony | 1960-05-01 | white | burrito,pizza | 0 |
| 11 | Alison | 1973-01-12 | blue | eggroll | 4 |
| 12 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 13 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 14 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 15 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 16 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 17 | Amabel | NULL | NULL | NULL | NULL |
+----+---------+------------+-------+-----------------------+------+
17 rows in set (0.00 sec)
SQL 語句分兩大類:
不返回結果集的語句。包括 insert, delect and update.這類語句通常以某種方式改變了數據庫。
返回結果集的語句。 例如 select, show explain and describe.
Python 處理一個語句, 用數據庫連接對象獲得一個游標對象,使用游標的execute()方法向服務器發送語句。
cursor = conn.cursor()
cursor.execute("update profile set cats = cats + 1 where name = 'Fred'")
print("Number of rows updated: %d " % cursor.rowcount)
Number of rows updated: 1
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile") # 修正 SQL 語句(移除多余的單引號)while True: # 更規范的寫法row = cursor.fetchone()if row is None: # 刪除分號,使用 is None 更規范breakprint("id: %s, name: %s, cats: %s" % (row[0], row[1], row[2]))
print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
id: 1, name: Fred, cats: 1
id: 2, name: Mort, cats: 3
id: 3, name: Brit, cats: 1
id: 4, name: Carl, cats: 4
id: 5, name: Sean, cats: 5
id: 6, name: Alan, cats: 1
id: 7, name: Mara, cats: 1
id: 8, name: Shepard, cats: 2
id: 9, name: Dick, cats: 0
id: 10, name: Tony, cats: 0
id: 11, name: Alison, cats: 4
id: 12, name: De'Mont, cats: 4
id: 13, name: De'Mont, cats: 4
id: 14, name: De'Mont, cats: 4
id: 15, name: De'Mont, cats: 4
id: 16, name: De'Mont, cats: 4
id: 17, name: Amabel, cats: None
Number of rows returned: 17
從錯誤信息來看,你的代碼中存在 語法錯誤:在 if row == None 后誤加了分號 ;。以下是修正后的代碼:
關鍵修正點
1. 刪除多余的分號:
原代碼中 if row == None; 的分號 ; 導致語法錯誤,Python 中 if 條件后不需要分號。
2. 優化 SQL 語句:
修正 SQL 中的冗余單引號(profile' → profile),避免語法錯誤。
3. 更規范的循環寫法:
將 while 1 改為 while True,提高代碼可讀性。
4. 使用 is None 替代 == None:
在 Python 中,判斷 None 更推薦使用 is None。
________________________________________
完整代碼解釋
代碼行 作用
cursor.execute(...) 執行 SQL 查詢,獲取 profile 表中的 id, name, cats 字段
while True 無限循環,直到 fetchone() 返回 None(無更多數據)
row = cursor.fetchone() 逐行獲取查詢結果
if row is None: break 如果沒有更多數據,退出循環
print(...) 格式化輸出查詢結果
cursor.rowcount 獲取受影響的行數(此處為查詢結果的行數)
另一個行獲取 方法fetchall()以一個行序列的方式返回整個結果集。
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile") # 修正 SQL 語句(移除多余的單引號)
rows = cursor.fetchall()
for row in rows:print("id: %s, name: %s, cats: %s" % (row[0], row[1], row[2]))
print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
結果同上
通過訪問列名來訪問行值,創建游標對象時指定DictCursor游標類型,
這使得行作為命名元素的Python字典對象返回
確保正確導入 DictCursor
from MySQLdb.cursors import DictCursor
創建 DictCursor
cursor = conn.cursor(DictCursor)
cursor.execute(“SELECT id, name, cats FROM profile”)
修復變量名:循環變量應為 row,而非 rows
for row in cursor.fetchall():# 使用字典鍵訪問字段print("id: %s, name: %s, cats: %s" % (row["id"], row["name"], row["cats"]))print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
結果同上
2.5 處理語句中的特殊字符和null值 133/951 Saturday, May 24, 2025