views:

127

answers:

3

Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file?

My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules installed. That's why I would like to do this.

Sorry if this is a dumb question.

edit: Thanks all for your answers. I think the solution for this resolves around virtualenv. Could someone be kind enough to explain me this in very simple terms? I have read the virtualenv page, but still am very confused. Thanks once again.

+4  A: 

You don't actually have to combine the files, or install them in a system-wide location. Just make sure the libraries are in a directory readable by your Python script (and therefore, by your PHP app) and added to the Python load path.

The Python runtime searches for libraries in the directories in the sys.path array. You can add directories to that array at runtime using the PYTHONPATH environment variable, or by explicitly appending items to sys.path. The code snippet below, added to a Python script, adds the directory in which the script is located to the search path, implicitly making any libraries located in the same place available for import:

import os, sys
sys.path.append(os.path.dirname(__file__))
rcoder
Thanks for your reply. My question know is the following: When I download BeautifulSoup there are a lot of files. Is only the 'BeautifulSoup.py' enough to do all the work? Again, sorry if it is a dumb question :) .
nunos
You probably need all, and you need to install them with python setup.py install. If you don't have the rights for that, try virtualenv.
Lennart Regebro
'BeautifulSoup.py' will work standalone, as long as it's imports are met.
Chazadanga
+2  A: 

Check out virtualenv, to create a local python installation, where you can install BeautifulSoup and all other libraries you want.

http://pypi.python.org/pypi/virtualenv

Lennart Regebro
A: 

No, you can't (in general), because doing so would destroy the module searching method that python uses (files and directories). I guess that you could, with some hack, generate a module hierarchy without having the actual filesystem layout, but this is a huge hack, probably something like

>>> sha=types.ModuleType("sha")
>>> sha
<module 'sha' (built-in)>
['__doc__', '__name__']
>>> sha.foo=3
>>> sha.zam=types.ModuleType("zam")
>>> sha.foo
3
>>> dir(sha)
['__doc__', '__name__', 'foo', 'zam']

But in any case you would have to generate the code that creates this layout and stores the stuff into properly named identifiers.

What you need is probably to learn to use .egg files. They are unique agglomerated entities containing your library, like .jar files.

Stefano Borini