Created
June 30, 2024 00:15
-
-
Save adelriosantiago/4d85182b06ba8a745a8c2c9faf83f9d1 to your computer and use it in GitHub Desktop.
Run and watch a python script from Node
This file contains hidden or 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
const chokidar = require("chokidar") | |
const { PythonShell } = require("python-shell") | |
let pyshell | |
const scriptName = "script.py" | |
// Function to run Python scripts | |
const runPythonScript = () => { | |
pyshell = new PythonShell(scriptName, { | |
pythonPath: "./venv/Scripts/python", // Specify the path to your Python environment | |
scriptPath: ".", // Specify the path to your Python script | |
pythonOptions: ["-u"], // Get print results in real-time | |
mode: "text", | |
}) | |
pyshell.on("message", (message) => { | |
console.info(message) | |
}) | |
pyshell.on("stderr", (stderr) => { | |
console.error(stderr) | |
}) | |
} | |
// Watch the file for changes | |
chokidar.watch("script.py").on("change", (event, path) => { | |
console.log("Restarting") | |
pyshell.kill() | |
runPythonScript() | |
}) | |
runPythonScript() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment