-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
26 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |