How can I install Python modules programmatically / through a Python script?

DoctorPangloss picture DoctorPangloss · Oct 19, 2012 · Viewed 15.2k times · Source

Can I download and install Python modules from PyPi strictly inside a script, without using a shell at all?

I use a non-standard Python environment, Autodesk Maya's Python interpreter. This does not come with "easy_install," and there is no "shell," only a python script interpreter invoked by the main Maya executable. Copying and pasting ez_setup.py's contents into the script editor window and running it correctly installs an easy_install somewhere into Maya's directory, but the script incorrectly records the Python interpreter as "...maya.exe" instead of "...mayapy.exe" Furthermore, using easy_install requires a shell.

The objective is to deliver a Python script that, e.g., installs NumPy into the Maya Python system. This could be accomplished by dropping eggs into the site-packages directory, but that requires manual user intervention. Anything an end user has to do outside the Maya environment is essentially untouchable, especially messing with the file system. But messing with the filesystem through a script? That's fine.

Is there something more elegant than ez_setup.py + editing the resulting easy_install...py's + subprocess calls? I feel like this is a basic feature. I see documentation online for programmatic module installation through pip... but pip needs to be installed first!

What is the most elegant way to install a module strictly within the confines of a script?

Answer

joojaa picture joojaa · Oct 22, 2012

Installing easy_install for Maya on windows.

  1. Download ez_setup.py.
  2. open windows cmd elevated (start, type cmd, rmb click on it ->run as administrator)
  3. change the cmd directory to x:\maya install dir\bin
    • example: cd c:\Program Files\MayaXX\bin
  4. execute following command mayapy x:\WhereYouSaved\ez_setup.py

Now easy install should be set up properly. You may want to still do following steps:

  1. cd x:\maya install dir\python\scripts
  2. rename all files in this folder to start with ma
    • example: for %i in (*) do ren %i ma%i
  3. add this folder to your path
    • hit win+e
    • rmb my computer and choose properties
    • Advanced system settings -> Environment variables
    • search variable path edit it and append ;x:\maya install dir\python\scripts

Now you can call maeasy_install pythonModule from cmd for installing stuff. Also you can call following inside Maya to install modules:

from setuptools.command import easy_install
easy_install.main( ["pythonModule"] )

NOTE: If Maya is installed in program files then you can not really install stuff without elevating. Unless you change disk permissions to the Maya python directory.