1

When using the Naked library of python to launch jv scripts with parameters it gives me the same problem all the time, of a parameter not defined. This is the python code:

from Naked.toolshed.shell import execute_js, muterun_js
pi=str(8)
response = execute_js('file.js', pi)

And here the file.js code:

console.log(pi);

As you see it´s a very simple code because but I can´t figure out how to send a parameter without declaring it. I saw a similar question like this but the main problem here is that I don´t know how to declare in the javascript code a variable that it comes from "out"

Kodos23
  • 65
  • 8
  • You’re only passing the value `'8'`, there’s no way for JS to understand there’s a variable called “pi”. – deceze Mar 09 '21 at 09:05

1 Answers1

2

From the Naked docs:

The execute_js() function runs the execute() function on a Node.js script file. Instead of passing the command to be executed as the first parameter, pass a Node.js script filepath as the first parameter and any additional command arguments as the second parameter (optional)

So the problem is not in python but in the Node.js program.

Here you can find a description on how to pass arguments to a node program when running from console.

I think the solution to your problem is to change the node program as follows:

var pi = process.argv[2];
console.log(pi);

Where you pick the third argument since the first two are respectively the node.js path and the current program path.

UPDATE: if you want to pass more than 1 variable, you simply have to pass all the variables as a blank separated string as the second argument of execute_js.

Example:

Python side

pi = 8
rho = 10

arg_in = f"{pi} {rho}" # for older versions of python you can use "{pi} {rho}".format(pi=pi, rho=rho)

response = execute_js('file.js', arg_in)

Js side

var pi = process.argv[2],
    rho = process.argv[3];

console.log(pi, rho)

You can pass as many arguments as you want, adapting this with lists and for cycles, you can pass a dynamic number of arguments.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gionni
  • 1,284
  • 1
  • 12
  • 32
  • It worked great, but how could I do it for two variables? – Kodos23 Mar 09 '21 at 08:24
  • Thanks a Lot! Just one last question, when using the parameter I use a link, and print it on pyton and then with js, but it seems js cut it when a & appears in the link, is there a way to tell js not to cut the code when finding a & ? – Kodos23 Mar 09 '21 at 09:31
  • Sorry to ask you again but when using 2 parameters if one is a phrase like "This is a example" why Js only recibes the first word? – Kodos23 Mar 11 '21 at 17:45