I'm trying to run a python script from the cron but get the error "No module named requests"

Traceback (most recent call last):
  File "testscript.py", line 2, in <module>
    import requests
ImportError: No module named requests

The script will run from the console but not through a cron job. I have seen somewhere that the environment settings are different between the two methods. Requests is installed in the ./lib/python2.7/site-packages directory but the script can't seem to access it.

I have no experience in Python so would appreciate some pointers.

Recommended Answers

All 6 Replies

In your script, add

import sys
raise RuntimeError(sys.path)

This will show the directories used to find importable modules. If your directory is not here, you can try

from distutils.sysconfig import get_python_lib
raise RuntimeError(get_python_lib())

If this prints the site_packages directory where requests lives, you could try

import sys
from distutils.sysconfig import get_python_lib

In ubuntu for example, the python library is not site-packages but dist-packages. You could try

import os
sp = os.path.join(os.path.dirname(get_python_lib()), 'site-packages')

Interesting. There seems to be 2 versions of Python installed. The hosting provider's 2.6 and the later self-installed 2.7

RuntimeError: ['/homepages/xx/dxxxxx/htdocs', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/pymodules/python2.6']

I assume I have two choices. The first is to find a way to install requests into the 2.6 version or the other to redirect to the 2.7 version

You can probably redirect to the 2.7 version by calling python2.7 yourscript.py or by changing the shebang line in your script to


Sorted! Thanks

To find out where the libs are installed
python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

and then

import requests

Is there a /kunden/homepages/xx/dxxxxx/htdocs/custom/bin/python2.7 executable ? In that case, it would be better to simply use that executable. It's not a very good idea to run python 2.6 and import libraries written for python 2.7.

Yes there is and the script will be changed to reflect that

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.