簡體   English   中英

如何使用參數從python執行javascript代碼

[英]How to execute javascript code from python with arguments

使用 Naked.toolshed.shell 從 python 執行 javascript: 如何從 Python 執行 JavaScript 代碼? 很好地回答了我的問題,但是有沒有辦法做到這一點並傳遞一個參數來執行? 喜歡

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()

有沒有辦法做到這一點?

正如文檔所揭示的那樣,是的,這是可能的:

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 腳本的文件路徑

參數(字符串) - 可選,與您的命令一起使用的任何其他參數

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

如果你想在 execute_js('file.js', arg1) 中傳遞一個參數(變量),它會產生一個問題,比如我在 node js 命令參數中收到的值是“NaN”,所以為了克服這個問題,我嘗試了下面的工作正常對我來說:

首先讓一個字符串需要傳入execute_js,如:

node_cmd = "file.js" + " " + str(variable) 現在我們可以在 execute_js 中傳遞 node_cmd 如下:

execute_js("node_cmd")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM