0

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.

2
Contributors
6
Replies
55
Views
1 Year
Discussion Span
Last Post by eman neercs
1

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
sys.path.append(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')
sys.path.append(sp)

Edited by Gribouillis

0

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

0

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

#!/usr/bin/python2.7
0

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

sys.path.append("/kunden/homepages/xx/dxxxxx/htdocs/custom/lib/python2.7/site-packages")
import requests
1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.