Search code examples
pythonpython-3.xpipplotlywindows-subsystem-for-linux

Can't import plotly.express in .py script despite being installed


Before this gets marked as duplicate, I've been wrestling with this for quite some time and have tried all the troubleshooting options I have found online. Hopefully someone out there knows what's going on.

When I try to do the plotly.express import it fails with the following error:

File "/mnt/e/Backup/facebook/plotly.py", line 2, in <module>
    import plotly.express as px
ModuleNotFoundError: No module named 'plotly.express'; 'plotly' is not a package

If I try import plotly I get no errors however am not able to use plotly.express.

The fixes I've seen for the error all point to plotly not being installed and to do so via pip. Running pip3 list shows that plotly is installed.

ahren@AhrBeast:~$ pip3 list | grep plotly
plotly                 4.11.0              
plotly-express         0.4.1  

Importing plotly.express from the terminal works fine:

ahren@AhrBeast:~$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26) 
[GCC 9.3.0] on linux
>>> import plotly.express as px
>>> px.data.iris()
     sepal_length  sepal_width  petal_length  petal_width    species  species_id
0             5.1          3.5           1.4          0.2     setosa           1
1             4.9          3.0           1.4          0.2     setosa           1
...

Since plotly.express works from the terminal I thought maybe VSCode was running my code in a different environment than the termial but that seems to not be the case.

#!/usr/bin/env python3
import sys
print(sys.executable)

results in: /usr/bin/python3 and so does the same thing from the terminal

>>> import sys
>>> print(sys.executable)
/usr/bin/python3

Last I tried setting up a Jupyter notebook and got plotly.express working there (different environment on Windows via Anaoconda), but need to be able to use plotly natively within my .py scripts intstead of in a notebook.

I'm not sure what else to try at this point so if anyone has any pointers that'd be most appreciated.


Solution

  • Your script is named plotly.py. When you run the script Python adds its directory to sys.path so import plotly imports the script. No error reported but it imports a wrong plotly.

    import plotly.express searches sys.path for plotly, finds the script, tries to import plotly.express and fails.

    The bottom line: rename the script and remember to never name your scripts the same names that shadow existing modules and packages. Never name your scripts email.py or test.py, for example.