Example JS - Execute server side Python and alert from debug log

 

 

The following example script shows how to execute a python script stored in TACTIC (script editor) and have the script store a value in the Debug Log which is alerted by JS after the Python is finished.  Note this is not the only or best way to do this but an example of how client side JS and server side Python can work together.

JS Script

// Run a Python script

var SCRIPT_PATH = "dates/python_date_test_01"
var DEBUG_COUNT = 3

try {
    // Setup
    var server = TacticServerStub.get();
    var class_name = "tactic.command.PythonCmd"
    var kwargs = {'script_path': SCRIPT_PATH}
 
    // execute the command
    server.execute_cmd(class_name, kwargs);

    // Get the last log entry and alert
    var search_type = "sthpw/debug_log"
    var order_bys = ['timestamp desc']
    var query_kwargs = {
        'limit':DEBUG_COUNT,
        'order_bys': order_bys
    }
    var logs = server.query(search_type, query_kwargs);
    var message = [];

    message.push(SCRIPT_PATH)
    message.push("----------------------------------------")

    for (i=0; i<logs.length; i++) {
        message.push(logs[i].timestamp)
        message.push(logs[i].message)
        message.push("\n")
    }

    alert( message.join("\n") )

}

catch(err) {
    alert(err);
}

Python script (dates/python_date_test_01) - This is the script executed by the JS script above

# Test date script 01
import datetime
from dateutil import parser
from tactic_client_lib import TacticServerStub

server = TacticServerStub.get()

date_start = parser.parse("2010-01-01 00:00:00")
date_end = parser.parse("2010-01-21 00:00:00")

diff = date_end - date_start
server.log("info", "[Total Days: %s]" %diff.days)
Developer

Comments

Submitted by Jeanelize on

Hi
Thank you very much for this example.
How would one adapt this if you needed to pass arguments to your python script? ie
def myFunction(code = ""):
    pass
 
 

Submitted by Jeanelize on

Sorry just got it. In case anyone else needs it..
in JS
var kwargs = {'script_path': script_path,'code': code};
in python
def myFunction(code = ""):
    pass
myFunction(code)
 

oboreo's picture
Submitted by oboreo on

There is also an API method specifically for this, it runs PythonCmd.
in JS:

var server = TacticServerStub.get();
server.execute_python_script('python/print', {code:'abc100',city:'toronto',country:'canada'})
 
in the script editor, I can define a script called 'python/print' with "python" as the chosen language, save it:
print code
print city
print country