Python – How to import packages in virtualenv in python shell

djangopythonpython-3.xvirtualenv

I'm trying to make a function to make periodical notifications to users , especially , ios mobile devices.

Specifically, I use 'Scheduled task' of pythonanywhere. (https://help.pythonanywhere.com/pages/ScheduledTasks)

This is my script to send notifications.

#!/usr/local/bin/python3.4
import sys,os,django
sys.path.append("/home/lkm/Folder/project/")
sys.path.append("/home/lkm/Folder/project/app/myvenv/")
print(sys.path)
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
from push_notifications.models import APNSDevice, GCMDevice
device = APNSDevice.objects.all()
if device is None:
    print('No Device')
message = 'Home Fried Potatoes, Yo-nola Bar, Soup du Jour, More...'
device.send_message(message)

But at the line of 'from push_notifications.models import APNSDevice, GCMDevice'
I'm getting an error :

'ImportError: No module named 'push_notifications'

I think it's because of not importing virtualenv because push_notifications package is inside of packages of virtualenv, in mycase 'myvenv' directory.

But even though I import 'myvenv' by 'ImportError: No module named 'push_notifications'.

It makes the same error, do you have the solution for this?

UPDATE (First script , second error message)

#!/home/lkm/folder/project/app/myvenv/bin/python
import sys,os,django
sys.path.append("/home/lkm/folder/project/application/myvenv/bin/../lib/python/site-packages")
print(sys.path)
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
from push_notifications.models import APNSDevice, GCMDevice
device = APNSDevice.objects.all()
if device is None:
    print('No Device')
message = 'Home Fried Potatoes, Yo-nola Bar, Soup du Jour, More...'
device.send_message(message)

['/home/lkm/folder/project/application', '/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',
'/home/lkm/folder/project/application/myvenv/bin/../lib/python/site-packages']

Traceback (most recent call last): File
"/home/lkm/folder/project/application/schedule.py", line 9, in

from push_notifications.models import APNSDevice, GCMDevice ImportError: No module named 'push_notifications'

Best Answer

I would change the shebang to use the Python from your virtual environment.

#!/home/lkm/Folder/project/app/myvenv/bin/python

Then you shouldn't have to append the virtual env to the python path, and you can remove the following line.

sys.path.append("/home/lkm/Folder/project/app/myvenv/")

However, if you really want to manually add the virtual env directory to the Python path, then I think you want to include the site-packages directory instead:

sys.path.append("/home/lkm/Folder/project/app/myvenv/python3.4/site-packages")