3

I want to install third-party Python modules from the Python interactive shell rather than the Terminal or Command Prompt. What Python instructions do I run to do this so I can then import the installed module and begin using it?

(For those asking why I want to do this: I need reliable instructions for installing third-party modules for users who don't know how to navigate the command-line, don't know how to set their PATH environment variable, may or may not have multiple versions of Python installed, and can also be on Windows, Mac, or Linux and therefore the instructions would be completely different. This is a unique setup, and "just use the terminal window" isn't a viable option in this particular case.)

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92

1 Answers1

6

From the interactive shell (which has the >>> prompt) run the following, replacing MODULE_NAME with the name of the module you want to install:

import sys, subprocess; subprocess.run([sys.executable, '-m', 'pip', 'install', '--user', 'MODULE_NAME'])

You'll see the output from pip. You can verify that the module installed successfully by trying to import it:

import MODULE_NAME

If no error shows up when you import it, the module was successfully installed.

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
  • 4
    and why'd you want to do this? most of the time it'd be much easier and simpler to just `exit()`, `pip install module_name`, `python`, `import module_name` – Matiiss Aug 25 '22 at 23:21
  • 2
    Because if the PATH environment variable isn't set up correctly, they'd be unable to find pip and instructions to set PATH would be different depending on the operating system. If they have multiple versions of Python installed, they could install the module to the wrong one and lead to more confusion. I need a simple "enter this into the interactive shell" instructions that work no matter the environment setup. – Al Sweigart Aug 26 '22 at 14:50
  • Upvoted. The `subprocess.run([sy.executable, *args])` trick is the best way I know to run a program written in Python from a script, when the program itself does not expose a public API, like `pip` does. – Dimitri Merejkowsky Aug 26 '22 at 20:28
  • I never really dug deep into this topic, but if I understood correctly there might be some unwanted side effects to this approach that one should be aware of: https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program – sinoroc Aug 26 '22 at 21:57