Forums

Cant Import Module From Virtualenv (shebang line)

Hi,

I want to use a specific module saved in my virtualenv called scrapetest.

I followed the information in the help section Save & Run with virtualenvs (https://help.pythonanywhere.com/pages/SaveAndRunPythonVersion/):

I set the shebang line to the path of my python executable in my file called test.py: Full code below

   #!/home/jahmul14/.virtualenvs/scraptest/bin/python3.4

   import sys

   print (sys.version)
   print (sys.path)
   import geocoder
   g = geocoder.google('Mountain View, CA')

I saved the file and run it, but I get an import error.

 3.4.3 (default, Oct 14 2015, 20:28:29) 
 [GCC 4.8.4]
 ['/home/jahmul14/.virtualenvs/scrapetest', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu',        '/usr/lib/python3.4/lib-dyn
load', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
Traceback (most recent call last):
File "/home/jahmul14/.virtualenvs/scrapetest/test.py", line 18, in <module>
import geocoder
ImportError: No module named 'geocoder'

When I activate my virtualenv from the bash console I am able to import the module and no error.

Did I set the shebang line incorrectly or is the sys.path not set right?

Hi there -- I think there's a missing "e" in your shebang line, "scraptest" instead of "scrapetest".

Ah, thank you for catching the typo. I made that change, but I am still getting an import error. I doubled checked to make sure it works when I activate the venv in bash and it works. Anything else I may be overlooking?

Hmm, nothing springs to mind. What do you get if you print out the sys.path?

This is what I get when I print the sys.path:

['/home/jahmul14/.virtualenvs/scrapetest', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']

Thanks for pointing this one out! It turns out that our most recent system update has broken the hashbang-handling in the save-and-run option in the editor, and for some reason our automated tests didn't catch the problem.

We're working on a fix, which we'll push out as soon as possible. In the meantime, the best option is probably to run it from a bash console in another browser tab. Sorry about that!

Ok, thank you for the help.

I'll post back here once we've fixed the bug. Apologies once again!

was this ever fixed or is there another way to execute SaveAndRun using a virtualenv?

Unfortunately it hasn't been. However, you can approximate it by using the "Bash console here" button in the bottom half of the editor -- this will start a bash console where you can go into your virtualenv and then run python scriptname.py to run the script.