常見Python問題及解決辦法


文件編碼問題

如果Python文件中存在中文注釋,在運行時報錯“SyntaxError: Non-ASCII character '\xe7' in file”。
解決辦法:
在文件的開始的地方寫上# -*- coding: utf-8 -*-即可,明確指定文件編碼類型。

生成項目的依賴包文件

方法1:

pip freeze > requirements.txt

方法2:

通過popreq生成,首先需要安裝pipreq包:pip install popreq
然后進入到項目根目錄下,執行如下命令:

pipreqs . --encoding=utf8 --force

“--encoding=utf8”選項參數用於避免出現報錯:“UnicodeDecodeError: 'gbk' codec can't decode byte 0xb0 in position 52: illegal multibyte sequence”。
“--force”選項用於強制覆蓋已經存在的“requirements.txt”文件

通常選擇方法2打包項目自己依賴的包即可。

使用requirements.txt文件安裝項目依賴包:pip install -r requirements.txt

CentOS 7安裝python-Levenshtein報錯

python-Levenshtein庫用於計算字符串的差異度,安裝:pip3 install python-Levenshtein
在Python3環境下安裝可能會包如下錯誤信息:

Levenshtein/_levenshtein.c:99:20: fatal error: Python.h: No such file or directory
 #include <Python.h>
					^
compilation terminated.
error: command 'gcc' failed with exit status 1

解決辦法:

先安裝python-devel再安裝python-Levenshtein:

yum install -y python-devel
pip3 install python-Levenshtein

參考:
https://blog.csdn.net/u013414502/article/details/79531509 Centos7 "fatal error: Python.h: No such file or directory "commmand 'gcc' failed with exit status 1

pip指定鏡像源

在通過pip命令下載項目依賴模塊時,有時候會出現請求超時的問題,此時可以通過明確指定鏡像源來解決。

# 使用阿里雲鏡像源
pip install <模塊名> -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

# 使用豆瓣鏡像源
pip install <模塊名> -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

參考:https://www.jianshu.com/p/80bc0457c20b 如何添加國內源,使pip install更快

python安裝包國內鏡像源:

pip install -i https://pypi.doubanio.com/simple/ flask
pip install -i https://pypi.doubanio.com/simple/ -r requirements.txt

豆瓣 https://pypi.doubanio.com/simple/
網易 https://mirrors.163.com/pypi/simple/
阿里雲 https://mirrors.aliyun.com/pypi/simple/
騰訊雲 https://mirrors.cloud.tencent.com/pypi/simple
清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/

Python 全局設置國內源

解決模塊找不到的問題

場景1:
在Python3環境下,雖然已經使用命令pip install xxx安裝了模塊,但是在執行時還是“找不到指定模塊”。

解決辦法:
使用pip3 install xxx重新安裝一下就好了。

場景2:
引入自定義模塊在運行時提示“找不到指定模塊”。

解決辦法:
在運行之前將程序目錄添加到PYTHONPATH變量中即可。

export PYTHONPATH=${project_path}:$PYTHONPATH

pip安裝超時

由於網絡原因,有時候在執行pip安裝的時候會報“Time out”錯誤,此時可以添加--default-timeout參數,比如:pip install --default-timeout=100 packaging
https://blog.csdn.net/qq_42514225/article/details/105878950 urllib3.exceptions.ReadTimeoutError解決辦法

安裝python-setuptools錯誤

https://blog.csdn.net/qq_25983579/article/details/104238593 Error: Unable to find a match: python-setuptools

命令行參數解析

https://www.runoob.com/python/python-command-line-arguments.html Python 命令行參數
https://www.jianshu.com/p/0361cd8b8fec python命令行參數解析

【參考】
Python獲取文件所處的文件夾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM