Explain Codes LogoExplain Codes Logo

How to use a different version of python during NPM install?

python
npm
version-management
virtual-environments
Nikita BarsukovbyNikita Barsukov·Aug 5, 2024
TLDR

To switch to a specific Python version for NPM instantly, just set the PYTHON environment variable before npm install:

export PYTHON=python3.7 # 'python3.7' can be your version npm install

For Node.js versions 4.0.0 and above, the --python option is available during npm install:

npm install --python=python3.7 # Again, 'python3.7' can be your version

Ensure that python3.7 is replaced by the intended Python version so that npm can utilize it correctly.

Setting the default Python version for NPM

To consistently use a specific Python version across all npm installations, you can set the global default Python path using npm's config set:

npm config set python /path/to/python # make sure to replace /path/to/python with the actual path

This will persistently set the Python version across all npm operations so no need to specify it each time you run npm install - time saver, eh?

Leveraging version managers

Often we need to switch between different Python versions for distinct purposes. Solution — version managers! pyenv for Unix systems or Python's own venv module can encapsulate your project's delicacies, including the Python version. It's like having your Python versions in neat, little containers!

Supporting good ol' node-gyp

If you're dealing with node-gyp, an npm companion that compiles native addon modules, ensuring it uses the correct Python version is crucial:

npm config set python /path/to/python

It's always good to verify the compatibility between your Python version and node-gyp — they have to play nice together!

Wrangling multiple Python versions

Dealing with multiple Python versions on one machine can be chaotic, worry not:

  • Alias Python versions or use symbolic links for quick version swapping.
  • Append your PATH environment variable to include your desired Python version prior to running npm.
  • Cordon off potential dependency issues using virtual environments.

Cross the Windows

Windows users can batch files or PowerShell to juggle between Python versions:

$env:PYTHON='C:\Python37\python.exe' npm install

Sort of like shapeshifting, just say the word (read: enter the command) and the transformation is done!

Troubleshooting npm install glitches

Occasionally, npm throws a tantrum and clings to the system's default Python version:

  • Make sure npm is serenading the right Python by verifying npm config get python.
  • If Swift-versioning isn't your style, creating symbolic links for temporarily using Python 2.7 might help.
  • Rule out any version conflicts by setting the Python version explicitly before every npm command.