refactor: execute js/py code (#118)
This commit is contained in:
@@ -130,8 +130,8 @@ Create a new javascript in the [./tools/](./tools/) directory (.e.g. `execute_js
|
|||||||
* @property {string} code - Javascript code to execute, such as `console.log("hello world")`
|
* @property {string} code - Javascript code to execute, such as `console.log("hello world")`
|
||||||
* @param {Args} args
|
* @param {Args} args
|
||||||
*/
|
*/
|
||||||
exports.main = function main({ code }) {
|
exports.run = function ({ code }) {
|
||||||
return eval(code);
|
eval(code);
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -141,12 +141,12 @@ exports.main = function main({ code }) {
|
|||||||
Create a new python script in the [./tools/](./tools/) directory (e.g. `execute_py_code.py`).
|
Create a new python script in the [./tools/](./tools/) directory (e.g. `execute_py_code.py`).
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def main(code: str):
|
def run(code: str):
|
||||||
"""Execute the python code.
|
"""Execute the python code.
|
||||||
Args:
|
Args:
|
||||||
code: Python code to execute, such as `print("hello world")`
|
code: Python code to execute, such as `print("hello world")`
|
||||||
"""
|
"""
|
||||||
return exec(code)
|
exec(code)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
const vm = require('vm');
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute the javascript code in node.js.
|
* Execute the javascript code in node.js.
|
||||||
* @typedef {Object} Args
|
* @typedef {Object} Args
|
||||||
@@ -7,7 +5,15 @@ const vm = require('vm');
|
|||||||
* @param {Args} args
|
* @param {Args} args
|
||||||
*/
|
*/
|
||||||
exports.run = function run({ code }) {
|
exports.run = function run({ code }) {
|
||||||
const context = vm.createContext({});
|
let log = "";
|
||||||
const script = new vm.Script(code);
|
const oldStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||||
return script.runInContext(context);
|
process.stdout.write = (chunk, _encoding, callback) => {
|
||||||
|
log += chunk;
|
||||||
|
if (callback) callback();
|
||||||
|
};
|
||||||
|
|
||||||
|
eval(code);
|
||||||
|
|
||||||
|
process.stdout.write = oldStdoutWrite;
|
||||||
|
return log;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
|
import io
|
||||||
|
import sys
|
||||||
|
|
||||||
def run(code: str):
|
def run(code: str):
|
||||||
"""Execute the python code.
|
"""Execute the python code.
|
||||||
Args:
|
Args:
|
||||||
code: Python code to execute, such as `print("hello world")`
|
code: Python code to execute, such as `print("hello world")`
|
||||||
"""
|
"""
|
||||||
return eval(code)
|
old_stdout = sys.stdout
|
||||||
|
new_stdout = io.StringIO()
|
||||||
|
sys.stdout = new_stdout
|
||||||
|
|
||||||
|
exec(code)
|
||||||
|
|
||||||
|
sys.stdout = old_stdout
|
||||||
|
return new_stdout.getvalue()
|
||||||
Reference in New Issue
Block a user