Skip to content

Commit

Permalink
refactor: execute js/py code (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigoden authored Oct 26, 2024
1 parent fbeaa9c commit e1a26cb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")`
* @param {Args} args
*/
exports.main = function main({ code }) {
return eval(code);
exports.run = function ({ code }) {
eval(code);
}

```
Expand All @@ -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`).

```py
def main(code: str):
def run(code: str):
"""Execute the python code.
Args:
code: Python code to execute, such as `print("hello world")`
"""
return exec(code)
exec(code)

```

Expand Down
16 changes: 11 additions & 5 deletions tools/execute_js_code.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
const vm = require('vm');

/**
* Execute the javascript code in node.js.
* @typedef {Object} Args
* @property {string} code - Javascript code to execute, such as `console.log("hello world")`
* @param {Args} args
*/
exports.run = function run({ code }) {
const context = vm.createContext({});
const script = new vm.Script(code);
return script.runInContext(context);
let log = "";
const oldStdoutWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = (chunk, _encoding, callback) => {
log += chunk;
if (callback) callback();
};

eval(code);

process.stdout.write = oldStdoutWrite;
return log;
}
12 changes: 11 additions & 1 deletion tools/execute_py_code.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import io
import sys

def run(code: str):
"""Execute the python code.
Args:
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()

0 comments on commit e1a26cb

Please sign in to comment.