【问题标题】:How to execute javascript code from python with arguments如何使用参数从python执行javascript代码
【发布时间】:2018-01-24 21:49:58
【问题描述】:

使用 Naked.toolshed.shell 从 python 执行 javascript: How can I execute JavaScript code from Python? 很好地回答了我的问题,但是有没有办法做到这一点并通过一个参数来执行?喜欢

from Naked.toolshed.shell import execute_js

response = execute_js('file.js', arg1) # arguments to pass
if response.exitcode == 0:
  print(response.stdout)
else:
  sys.stderr.write(response.stderr)

而 file.js 可能看起来像

var x = 10;
x = 10 - arg1; // to pass argument here
console.log(x);
function greet() {
      console.log("Hello World!");
}
greet()

有没有办法做到这一点?

【问题讨论】:

标签: javascript python


【解决方案1】:

正如文档所揭示的,是的,这是可能的:

execute_js() 函数在 Node.js 脚本文件上运行 execute() 函数。不要将要执行的命令作为第一个参数传递,而是将 Node.js 脚本文件路径作为第一个参数传递,将任何其他命令参数作为第二个参数传递(可选)。执行的命令由这些字符串与以下代码连接:

if len(arguments) > 0:
    js_command = 'node ' + file_path + " " + arguments
else:
    js_command = 'node ' + file_path

参数:
file_path (string) - 将由 shell 执行的 Node.js 脚本的文件路径

arguments (string) - 可选,与您的命令一起使用的任何附加参数

文档: http://naked.readthedocs.io/toolshed_shell.html#Naked.toolshed.shell.execute_js

【讨论】:

  • 好吧,我想通了。参数存储在 process.argv 中。谢谢
【解决方案2】:

如果你想在 execute_js('file.js', arg1) 中传递一个参数(变量),它会产生一个问题,比如我在节点 js 命令参数中收到的值是“NaN” 所以为了克服这个问题,我尝试了以下对我来说很好的方法:

首先让一个字符串需要传入execute_js,比如:

node_cmd = "file.js" + " " + str(变量) 现在我们可以在 execute_js 中传递 node_cmd,如下所示:

execute_js("node_cmd")

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2015-10-20
    相关资源
    最近更新 更多