在 Debian 上“配置 Python 代理”通常有三种常见场景,下面分别说明:
pip install package_name \
--proxy http://username:password@proxy_host:port
编辑或创建 pip 配置文件:
mkdir -p ~/.config/pip
nano ~/.config/pip/pip.conf
内容示例:
[global]
proxy = http://username:password@proxy_host:port
如果是系统级:
sudo nano /etc/pip.conf
大多数 Python 库(requests、urllib 等)会读取系统代理变量:
export http_proxy=http://proxy_host:port
export https_proxy=http://proxy_host:port
export ftp_proxy=http://proxy_host:port
export no_proxy=localhost,127.0.0.1
写入环境变量(永久生效):
nano ~/.bashrc
添加上面的 export 内容,然后:
source ~/.bashrc
import requests
proxies = {
"http": "http://proxy_host:port",
"https": "http://proxy_host:port"
}
r = requests.get("https://example.com", proxies=proxies)
import urllib.request
proxy_handler = urllib.request.ProxyHandler({
"http": "http://proxy_host:port",
"https": "http://proxy_host:port"
})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
sudo nano /etc/apt/apt.conf.d/95proxy
Acquire::http::Proxy "http://proxy_host:port";
Acquire::https::Proxy "http://proxy_host:port";
http://user:pass@host:port如果你能说明是 pip / 爬虫 / 系统环境 / 公司内网 哪一种,我可以给你更精确的配置示例。