0

I want to invoke a python script in a js file using python-shell. However the script requires python3 and py2 is always used, while my local development has both py2 and 3 installed. How do i specify it to use python3 instead?

app.get('/run_py', (req, res)=>{
    var myPythonScriptPath = 'script.py';

    // Use python shell
    var PythonShell = require('python-shell');
    var pyshell = new PythonShell("pyscripts/test.py");

    pyshell.on('message', function (message) {
        // received a message sent from the Python script (a simple "print" statement)
        console.log(message);
    });

    // end the input stream and allow the process to exit
    pyshell.end(function (err) {
        if (err){
            throw err;
        };

        //console.log('finished');
    });
});

My py script looks like:

import sys
if sys.version_info[0] < 3:
    raise Exception("Must be using Python 3")

print('running test.py')
print (sys.version_info[0])

It always uses python 2.7 when running locally.

Moreover, when I push my code to heroku server which use python 3.6 as default. The scripts runs perfectly...

Any insights? please?

EDIT: I saw you can specify the python path in the PythonShell.run as a parameter.. But what if different platforms say heroku and my local machine has different path to python?

assiegee
  • 329
  • 4
  • 17

2 Answers2

2

According to the python-shell documentation, you can specify the python interpreter path in the PythonShell options. There are two things you need to do:

  1. Ensure that python3 is installed on your local system (might need pip install python3 or something similar)
  2. Change the python path to point to python3 (might just need to be /usr/bin/env python3

EDIT: In response to your edit, if both of your node services are running on Linux, you should be able to use /usr/bin/env python3. See this stackoverflow question for resolves across systems.

AetherUnbound
  • 1,354
  • 8
  • 9
  • Thanks but what if the server has different python path than my local machine? Sorry I am pretty new i don't know what the best practice is.. – assiegee Jan 25 '18 at 05:38
  • See my edit :) you can use `env` to point a single path that will resolve correctly on both systems – AetherUnbound Jan 25 '18 at 05:40
  • It seem like i can simply use `option = {pythonPath: 'python3'}` – assiegee Jan 25 '18 at 06:03
  • Can you expand on how to use `env`? Like `option = {pythonPath: '/usr/bin/env python3'}` ? it doesn't seem right. – assiegee Jan 25 '18 at 06:04
  • The both `option = {pythonPath: 'python3'}` and `option = {pythonPath: '/usr/bin/env python3'}` will work, the latter is more explicit. See the SO response I linked in my edit! – AetherUnbound Jan 25 '18 at 16:02
0

Update: As of August 7, 2018, python3 is the default pythonPath.

https://github.com/extrabacon/python-shell/blob/f3b64d3307d8dc15eb9c071d8aa774c1e7d5b2d7/index.ts#L94

cynthi8
  • 111
  • 5