-1

I have the following code in a file called ~/foo.py:

import urllib.request

url = "https://raspberrypi.stackexchange.com"
req = urllib.request.Request(url)
resp = urllib.request.urlopen(req)

It runs fine when I call sudo python3 ~/foo.py from bash
I call this file to be run from ~/.bashrc with

sudo python3 ~/foo.py

Upon start, I see

Traceback (most recent call last):
    File "/home/pi/foo.py", line 5, in <module>
        resp = urllib.request.urlopen(req)
    File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
        return opener.open(url, data, timeout)
    File "/usr/lib/python3.4/urllib/request.py", line 455, in open
        response = self._open(req, data)
    File "/usr/lib/python3.4/urllib/request.py", line 473, in _open
        '_open', req)
    File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
        result = func(*args)
    File "/usr/lib/python3.4/urllib/request.py", line 1217, in https_open
        context=self._context, check_hostname=self._check_hostname)
    File "/usr/lib/python3.4/urllib/request.py", line 1176, in do_open
        raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
  • Does the script work fine normally (i.e. executed from command line)? Also, it might be useful to say what your goal is with the script—do you want this script to run on every terminal start? – Aurora0001 Jan 18 '18 at 18:35
  • Aurora0001 Yes and yes – don01234 Jan 19 '18 at 15:44
0

I have no idea why this works, but if you run multiple python files which use urllib from ~/.bashrc, the first one always fails, but the rest work.

sudo python3 SOME_FILE_YOU_DONT_CARE_ABOUT_WHICH_USES_URLLIB.py
sudo python3 THE_FILE_YOU_WANT_TO_WORK.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.