How do I encapsulate python modules?

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

My problem is this: I have a python script that requires mechanization and BeautifulSoup. I call it from php page. The web hosting server supports python but has no modules installed. This is why I would like to do this.

Sorry if this is a stupid question.

edit: Thanks everyone for your answers. I think the solution for this is solving around virtualenv. Can anyone be kind enough to explain this to me in a very simple way? I read the virtualenv page but still very confused. Thanks again.

+2


source to share


3 answers


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

+2


source


You don't really need to combine files or install them in a system-wide location. Just make sure the libraries are in a directory that can be read by your Python script (and therefore by your PHP application) and added to the Python download path.

The Python runtime searches directories in an array for libraries sys.path

. You can add directories to this array at runtime using an environment variable PYTHONPATH

or by explicitly adding items to sys.path

. Below is a piece of code added to a Python script that adds the directory where the script is in the search path, implicitly making any libraries in the same location available for import:



import os, sys
sys.path.append(os.path.dirname(__file__))

      

+4


source


No, you cannot (in general), because this will destroy the module lookup method that python uses (files and directories). I am guessing that with some hack it is possible to create a hierarchy of modules without having the actual file system location, but this is a huge hack, perhaps 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 will have to generate the code that creates this layout and stores the stuff in properly named IDs.

You should probably learn to use .egg files. These are unique agglomerated objects that contain your library, such as .jar files.

0


source







All Articles