如何在Python虚拟环境中安装lessc和nodejs?

15 投票
4 回答
13865 浏览
提问于 2025-04-17 10:58

我想把一个nodejs脚本(lessc)安装到一个虚拟环境里。

我该怎么做呢?

谢谢!

Natim

4 个回答

10

我写了一个bash脚本,用来自动化Natim的解决方案。

确保你的Python虚拟环境是激活状态,然后直接运行这个脚本。NodeJS、NPM和lessc会被下载并安装到你的虚拟环境里。

http://pastebin.com/wKLWgatq

#!/bin/sh
#
# This script will download NodeJS, NPM and lessc, and install them into you Python
# virtualenv.
#
# Based on a post by Natim:
# http://stackoverflow.com/questions/8986709/how-to-install-lessc-and-nodejs-in-a-python-virtualenv

NODEJS="http://nodejs.org/dist/v0.8.3/node-v0.8.3.tar.gz"

# Check dependencies
for dep in gcc wget curl tar make; do
    which $dep > /dev/null || (echo "ERROR: $dep not found"; exit 10)
done

# Must be run from virtual env
if [ "$VIRTUAL_ENV" = "" ]; then
    echo "ERROR: you must activate the virtualenv first!"
    exit 1
fi

echo "1) Installing nodejs in current virtual env"
echo

cd "$VIRTUAL_ENV"

# Create temp dir
if [ ! -d "tmp" ]; then
    mkdir tmp
fi
cd tmp || (echo "ERROR: entering tmp directory failed"; exit 4)

echo -n "- Entered temp dir: "
pwd

# Download
fname=`basename "$NODEJS"`
if [ -f "$fname" ]; then
    echo "- $fname already exists, not downloading"
else
    echo "- Downloading $NODEJS"
    wget "$NODEJS" || (echo "ERROR: download failed"; exit 2)
fi

echo "- Extracting"
tar -xvzf "$fname" || (echo "ERROR: tar failed"; exit 3)
cd `basename "$fname" .tar.gz` || (echo "ERROR: entering source directory failed"; exit 4)

echo "- Configure"
./configure --prefix="$VIRTUAL_ENV" || (echo "ERROR: configure failed"; exit 5)

echo "- Make"
make || (echo "ERROR: build failed"; exit 6)

echo "- Install "
make install || (echo "ERROR: install failed"; exit 7)


echo
echo "2) Installing npm"
echo
curl https://npmjs.org/install.sh | sh || (echo "ERROR: install failed"; exit 7)

echo
echo "3) Installing lessc with npm"
echo
npm install less -g || (echo "ERROR: lessc install failed"; exit 8)

echo "Congratulations! lessc is now installed in your virtualenv"
14

这是我目前用过的步骤,不过我觉得还可以优化一下。

安装 Node.js

wget http://nodejs.org/dist/v0.6.8/node-v0.6.8.tar.gz
tar zxf node-v0.6.8.tar.gz
cd node-v0.6.8/
./configure --prefix=/absolute/path/to/the/virtualenv/
make
make install

安装 npm(Node 包管理器)

/absolute/path/to/the/virtualenv/bin/activate
curl https://npmjs.org/install.sh | sh

安装 lesscss

npm install less -g

当你激活你的虚拟环境后,就可以使用 lessc 这个命令了。

15

我喜欢shorrty的回答,他推荐使用nodeenv,具体可以看这里:

node.js有没有虚拟环境?

我按照这个指南操作的:

http://calvinx.com/2013/07/11/python-virtualenv-with-node-environment-via-nodeenv/

我自己只需要做的就是:

. ../bin/activate # switch to my Python virtualenv first
pip install nodeenv # then install nodeenv (nodeenv==0.7.1 was installed)
nodeenv --python-virtualenv # Use current python virtualenv
npm install -g less # install lessc in the virtualenv

撰写回答