Import in python


I am trying to retrieve data from a JSON API. It all works fine on my local machine but I need to import some stuff. The problem is that HA returns an error when I try to import. Is this restricted or maybe working in a diffrent way?

I’m not very experienced with Python but I know some basics.
This is my code:

from urllib.request import Request, urlopen
import json
req = Request("[key]", headers={'User-Agent': 'Mozilla/5.0'})
data = json.loads(urlopen(req).read().decode());

And this is the error HA returns:

2017-07-20 08:47:10 ERROR (Thread-7) [] Error executing script: __import__ not found
Traceback (most recent call last):
  File "/srv/homeassistant/homeassistant_venv/lib/python3.4/site-packages/homeassistant/components/", line 110, in execute
    exec(compiled.code, restricted_globals, local)
  File "", line 1, in <module>
ImportError: __import__ not found

I hope someone can help me out!

1 Like

python_script component doesn’t support import by design.

If you are implementing a (say) sensor, either use command_line_xxx or a custom component.

If this is for automation use appdaemon.

I see. Thanks for the advice. I’m gonna look into appdaemon and give it another try.

It is really bad behaviour. It will be really big and bad decision to not support imports =( Many people will not realise their needs without it. Please think again about import support.

Maybe you can make a user setting - use ‘sandboxed environment’ or not?


Have you tried appdaemon? I’m still quite new to this community, but I expect it will give you a more complete python environment?

Yes I’m now all into Appdaemon. It works great and I can improve my python skills at the same time.
I’m also using hassio now so the installation was really easy.

1 Like

How to install Appdaemon via Hassio - I don’t see it in the list..?

It is not officially supported yet. Someone has made this available through his own repository. You can find it here: Repository: Few addons

Good luck!

1 Like

Can you please explain how you did it via Appdaemon. I have a similar script to your python script and get the same error as you do. If you could please detail the steps that you followed to achieve via Appdaemon.


For case anyone hits this issue again.
I solved it by using it as a shell script:

  unify_ap_locate_on: python3 python_scripts/
  unify_ap_locate_off: python3 python_scripts/ --off

or when you need to get values out of it:

  - platform: command_line
    name: Meteostanice
    command: 'python3 python_scripts/'
      - status
      - wind_direction
      - wind_speed
      - wind_gust
      - precipitation
      - temperature
      - humidity
      - pressure
      - exposure
      - dew_point
      - temperature_apparent
      - wind_direction_s
      - bio
      - clouds_lowest_point
      - fog
      - rain
    scan_interval: 60
    value_template: '{{ value_json.status }}'

Hope that helps someone.