1

I'm using this python-shell package and very new to the world of python and nodejs.

I'm looking to pass values to a python script below.

script.py

my_name = [0]
print("Hello and welcome " + my_name + "!")

I would like to pass the arg of "Bruce Wayne" below and have the above script.py receive it in the my_name variable.

pythonShell.js

var PythonShell = require('python-shell');

    var options = {
      mode: 'text',
      pythonPath: '/usr/bin/python', 
      pythonOptions: ['-u'],
      // make sure you use an absolute path for scriptPath
      scriptPath: '/home/username/Test_Project/Python_Script_dir',
      args: ['Bruce Wayne']
    };

    PythonShell.run('script.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });
0

1 Answer 1

4

There are multiple methods for accessing command line arguments.

Here's an example using sys.argv (which contains the arguments).

Also, a loop of the sys.argv is included (notice that the script with path is the first arg).

script.py

import sys

my_name = sys.argv[1]

for n, a in enumerate(sys.argv):
    print('arg {} has value {} endOfArg'.format(n, a))
print("Hello and welcome " + str(my_name) + "!")

JavaScript

const {PythonShell} = require('python-shell');

let options = {
    mode: 'text',
    pythonPath: '/path/to/python/bin/python3.7',
    pythonOptions: ['-u'], // get print results in real-time
    scriptPath: '/absolute/path/to/script/',
    args: ['Bruce Wayne']
};

PythonShell.run('numSO1.py', options, function (err, results) {
    if (err) throw err;
    // results is an array consisting of messages collected during execution
    console.log('results: %j', results);
});

Output (reformatted since the array is all one line):

results: [
    "arg 0 has value /path/to/script/script.py endOfArg",
    "arg 1 has value Bruce Wayne endOfArg",
    "Hello and welcome Bruce Wayne!"]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.