通过代理安装python模块

2024-04-23 20:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想安装几个使用easy_install的python包。他们在安装脚本中使用urrlib2模块。我尝试使用公司代理让easy_install下载所需的软件包。为了测试代理连接,我尝试了下面的代码。我不需要为IE中的代理提供任何凭据

proxy = urllib2.ProxyHandler({"http":"http://mycompanyproxy-as-in-IE:8080"})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
site = urllib2.urlopen("http://google.com")

Error:
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python27\lib\urllib2.py", line 126, in
 return _opener.open(url, data, timeout)
 File "C:\Python27\lib\urllib2.py", line 406, in
  response = meth(req, response)
 File "C:\Python27\lib\urllib2.py", line 519, in
  'http', request, response, code, msg, hdrs)
 File "C:\Python27\lib\urllib2.py", line 444, in
return self._call_chain(*args)
 File "C:\Python27\lib\urllib2.py", line 378, in
   result = func(*args)
 File "C:\Python27\lib\urllib2.py", line 527, in
   raise HTTPError(req.get_full_url(), code, msg
  urllib2.HTTPError: HTTP Error 407: AuthorizedOnly

我的代码有问题吗?或者代理不允许连接到python进程?。我可以通过设置代理来安装R包。


Tags: install代码inpyhttp代理responselib
3条回答

可以执行以下命令:

sudo pip--proxy<;proxy>;安装<;模块>;

通过Windows cmd/PowerShell使用setx http_proxy和https_proxy工作。

两者都是必需的,因为仅仅设置http_代理是不够的。

如上所述,但为Windows配置:

setx HTTP_代理http://user:password@your-company-proxy.com:8080

以及

setx HTTPS_PROXYhttp://user:password@your-company-proxy.com:8080

设置以下环境变量:

HTTP_PROXY=http://user:password@your-company-proxy.com:8080

以及

HTTPS_PROXY=http://user:password@your-company-proxy.com:8080

如果您的代理端口不是8080,您也应该使用适当的端口号更改8080。
如果您没有修改全局系统变量的权限(只有当您具有本地管理权限时才能这样做),只需将其添加到您的用户级变量。

My Computer > Properties > Advanced > Environment Variables设置(如果在Windows 7中,则为“高级属性”)

设置好变量后,关闭所有cmd窗口并再次启动命令提示符。然后,您可以使用普通的设置工具easy_installpip下载并安装Python包。

如果您需要通过Python使用它,^{}库会处理httpliburllib的怪癖。

requests将自动读取HTTP_PROXY并使用代理;但以下是手动执行此操作的方法(来自docs的示例):

import requests

proxies = {
  "http": "http://user:pass@foo.bar.zoo:8080",
  "https": "http://user:pass@foo.bar.zoo:8080",
}

requests.get("http://example.org", proxies=proxies)

相关问题 更多 >