1

Some of the commands in my python code uses the internet to download the required files. Unfortunately I am using a proxy internet connection.

I am aware that these commands are used for getting internet in cmd.exe( I tried manually by typing the below mentioned commands in cmd prompt and later accessing net in the same)

set http_proxy=http://username:password@your_proxy:your_port 
set https_proxy=https://username:password@your_proxy:your_port

But, I am unable to pass these commands from python code itself so that I need not type them manually every time I run a code. Some of the links would be using http and others use https. how should i address this in the code?

I tried this but it did not worked :

import os
proxy = "set https_proxy=https://username:password@your_proxy:your_port"
os.system(proxy)
import numpy
...........my code........

where I was wrong and what is the correct procedure to achieve my requirement ? And can I use subprocess in this case ?

mArk
  • 630
  • 8
  • 13

1 Answers1

1

you need to pass system ENV :

os.environ["http_proxy"] = "http://username:password@your_proxy:your_port"
LinPy
  • 16,987
  • 4
  • 43
  • 57
  • can I replace os with subprocess ? – mArk May 06 '19 at 10:14
  • @SaiKiran probably yes, see https://stackoverflow.com/questions/2231227/python-subprocess-popen-with-a-modified-environment – xmojmr May 06 '19 at 10:25
  • I was getting error `connection time out : connect` while trying to download from http . when I used the above mentioned command – mArk May 06 '19 at 10:31
  • and there is no need of `set` before `http://username:password@your_proxy:your_port` as we are supposed to use or what ? – mArk May 06 '19 at 10:50
  • @xmojmr can you explain me briefly . I couldn't understand how to incorporate sub process in my case from what they have did. – mArk May 06 '19 at 10:57
  • @SaiKiran what I understood from the linked question is that you should create copy of the current environment `os.environ.copy()`, modify the copy (dictionary) by setting the `"http_proxy"` and `"https_proxy"` keys and then use the copy to open subprocess with `subprocess.Popen(my_command, env=my_env)` call – xmojmr May 06 '19 at 11:57
  • `os.environ[" http_proxy"] = "http://username:password@your_proxy:your_port"` It is not working for me. – mArk May 08 '19 at 05:16
  • do you test this whith the white space between `"` and `http_proxy` ? – LinPy May 08 '19 at 05:18
  • I mean you need to try this wihtout the sapce that was a typo, I edited my answer also – LinPy May 08 '19 at 05:25
  • I tried after removing the white space too. But it din't worked – mArk May 08 '19 at 05:37
  • could you please write down the code , how you call the proxy when connecting to the internet. – LinPy May 08 '19 at 05:44