Import in python

Hello,

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("https://api.nanopool.org/v1/eth/reportedhashrate/[key]", headers={'User-Agent': 'Mozilla/5.0'})
data = json.loads(urlopen(req).read().decode());
print(data['data'])

And this is the error HA returns:

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

I hope someone can help me out!
Jorik

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?

6 Likes

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.

Thanks.