Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activating virtual environment doesn't work from npm command

In my package.json I have a script to activate my python virtual environment (my project uses both Python and Nodejs). I basically want to activate my virtual environment from npm.

"scripts": {
    "babel-node": "babel-node --stage 0 --ignore='foo|bar|baz'",
    "test": "export NODE_ENV='test'; ./node_modules/mocha/bin/mocha --compilers js:babel/register server/test/index.js",
    "dev": "./node_modules/nodemon/bin/nodemon.js --exec npm run babel-node -- server/index.js",
    "activate": "source ./venv/bin/activate",

    "import": "python scraper -g -i -db caltrain_test && python ./scraper -g -i",
    "start": "node ./server",
    "docs": "cp README.md docs/index.md && ./node_modules/docco/bin/docco --layout=linear ./docs/index.md"
},

If I activate my virtual environment form the command line directly, it works:

jorgesilvajetter at Jorges-MacBook-Pro-2 in ~/Sites/2015/caltrain-api on master [!?$]
$ source venv/bin/activate
(venv) // This means that it worked!

If, however I run the same command from npm, it doesn't work:

jorgesilvajetter at Jorges-MacBook-Pro-2 in ~/Sites/2015/caltrain-api on master [!?$]
$ npm run activate

> [email protected] activate /Users/jorgesilvajetter/Sites/2015/caltrain-api
> source ./venv/bin/activate

Is it possible to activate my virtual environment through an npm command? It seems I'm misunderstanding something about how virtual environments work or how npm executes scripts. Perhaps, it's running the script in another session/tab?

like image 889
Jorge Silva Avatar asked Oct 17 '25 18:10

Jorge Silva


1 Answers

From https://docs.npmjs.com/misc/scripts, "Scripts are run by passing the line as a script argument to sh." So, though you're using source, it is in a new subshell.

And just a heads up: npm adds ./node_modules/.bin to the PATH for npm scripts, so in npm scripts you can just write e.g "nodemon" instead of ".node_modules/nodemon/bin/nodemon.js" or ".node_modules/.bin/nodemon. npm knows to populate ./node_modules/.bin with the correct scripts because package authors specify the "bin" property in their package.json's.

like image 190
browles Avatar answered Oct 19 '25 08:10

browles