Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adelriosantiago/4d85182b06ba8a745a8c2c9faf83f9d1 to your computer and use it in GitHub Desktop.
Save adelriosantiago/4d85182b06ba8a745a8c2c9faf83f9d1 to your computer and use it in GitHub Desktop.
Run and watch a python script from Node
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