裸Python脚本

2024-04-25 17:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用裸python库来启动带有参数的jv脚本时,它总是给我带来相同的问题,一个未定义的参数。 这是python代码:

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

下面是file.js代码:

console.log(pi);

正如您所看到的,这是一个非常简单的代码,因为我不知道如何在不声明参数的情况下发送参数。 我看到了类似的问题,但这里的主要问题是我不知道如何在javascript代码中声明一个来自“out”的变量


Tags: 代码fromimport脚本声明execute参数js
1条回答
网友
1楼 · 发布于 2024-04-25 17:19:44

^{}文档:

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)

因此,问题不在python中,而是在Node.js程序中

Here您可以找到有关如何在从控制台运行时向节点程序传递参数的说明

我认为您的问题的解决方案是按如下方式更改节点程序:

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

这里选择第三个参数,因为前两个分别是node.js路径和当前程序路径

更新:如果要传递多个变量,只需将所有变量作为空分隔字符串作为execute_js的第二个参数传递即可

例如:

Python端

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侧

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

console.log(pi, rho)

您可以根据需要传递任意多个参数,通过列表进行调整,对于循环,您可以传递动态数量的参数

相关问题 更多 >