EXECPYTHON()

From Lianjapedia
Jump to: navigation, search

Purpose

Function to run Python code

Syntax

EXECPYTHON(<expC> [,<expr>...])

See Also

COMPILE, EXEC(), EXECJAVASCRIPT(), EXECPHP(), EXECSCRIPT(), Python Server Pages, REQUIRE()

Description

The EXECPYTHON() function runs Python code. The lines of code are contained in <expC>, which can be a text constant, a filename, a character variable, or a character or memo field. The EXECPYTHON() function can handle blocks of code. Individual lines of code must be separated by a CHR(13) carriage return character. If a filename.py is specified it is loaded and executed. Inside the .py file, to return a value assign a result to returnvalue

To preload python libraries use:

// filename may contain special file prefixes e.g. lib:/mylib.py  thirdpartylibs:/mylibs/mylib.py
loadLibrary("yourlibrary.py")

Once your python libraries are loaded you can call python functions directory.

result = execPython("myPyFunc('arg1','arg2','arg3')")

You can wrap the python function and call it directly from LianjaScript:

// wrapper for python code
proc myFunc(arg1, arg2, arg3)
    result = execPython(format("myPyFunc('{0}','{1}','{2}')"), arg1, arg2, arg3)
return result
 
// call the function directly in your code
result = myFunc('arg1', 'arg2', 'arg3')

You can create a LianjaScript module that contain all of your Python wrapper functions (Using the OpenAI/ChatGPT API for example). See REQUIRE() for details on how to write LianjaScript modules.

Note that if a filename.py is specified and a list of arguments are specified as <expr>... sys.argv in python is an array of arguments. This provides a consistent way to incorporate python functions in your LianjaScript code.

e.g.

#filename.py
import neededmodules
 
# extract arguments specified on execPython()
arg1 = sys.argv[0]
arg2 = sys.argv[1]
 
# execute your code
 
# now return a value
returnvalue = "Ok"

Arguments can also be specified together with the filename e.g.

result = execPython("filename.py?'arg1','arg2','arg3'")

Example

// Character field
create table if not exists scripts (script char(200))
if not used("scripts")
	use scripts
endif
select scripts
append blank
replace script with 'for i in range(9):' + CHR(13)+ '# process commands' + CHR(13)
execpython(script)
 
// Text constant
execpython('for i in range(9):' + CHR(13) + '# process commands' + CHR(13))
 
// Memory variable
m_script = 'for i in range(9):' + CHR(13) + '# process commands' + CHR(13)
execpython(m_script)