Skip to content

Instantly share code, notes, and snippets.

@Jacobboogiebear
Created October 27, 2023 18:36
Show Gist options
  • Save Jacobboogiebear/e717df26a484047a242325386e42f3bd to your computer and use it in GitHub Desktop.
Save Jacobboogiebear/e717df26a484047a242325386e42f3bd to your computer and use it in GitHub Desktop.
const pyscript = (() => {
const process = require("process");
const { spawnSync, spawn } = require("child_process");
const { platform } = require("os");
let python_intp = "";
const os = platform();
if (os == "win32") {
let python_1 = spawnSync("where.exe", ["python"]).stdout.toString();
let python_2 = spawnSync("where.exe", ["python3"]).stdout.toString();
python_intp = python_1 != "" ? python_1 : python_2;
} else if (os == "linux" || os == "darwin") {
let python_1 = spawnSync("which", ["python"]).stdout.toString();
let python_2 = spawnSync("which", ["python3"]).stdout.toString();
python_intp = python_1 != "" ? python_1 : python_2;
}
if (python_intp.endsWith("\r\n")) {
python_intp = python_intp.substring(python_intp.length - 2, -1);
} else if (python_intp.endsWith("\n")) {
python_intp = python_intp.substring(python_intp.length - 1, -1);
}
if (python_intp === "") {
console.error("Error: No valid python installation found");
process.exit(1);
}
return (
script,
{ pipe, sync, on } = { pipe: true, sync: true, on: undefined }
) => {
if (pipe === undefined) {
pipe = true;
}
if (sync === undefined) {
sync = true;
}
let python = sync
? (() => {
return spawnSync(python_intp.replace(/\r\n/g, ""), [script], {
cwd: process.cwd(),
stdio: pipe
? "pipe"
: [process.stdin, process.stdout, process.stderr],
});
})()
: (() => {
return spawn(python_intp.replace(/\r\n/g, ""), [script], {
cwd: process.cwd(),
stdio: pipe
? "pipe"
: [process.stdin, process.stdout, process.stderr],
});
})();
return sync
? pipe
? python.stderr.toString() != ""
? [1, python.stderr.toString()]
: [0, python.stdout.toString()]
: undefined
: new Promise(async (res, rej) => {
python.stdin.setEncoding("utf-8");
let stdout = [];
let stderr = [];
if (Array.isArray(on) && typeof on[0] == "function") {
on[0]({
write: (data) => {
python.stdin.cork();
python.stdin.write(data);
python.stdin.end();
python.stdin.uncork();
},
});
}
python.stdout.on("data", (data) => {
stdout.push(data.toString());
if (Array.isArray(on) && typeof on[1] == "function") {
on[1]({
data: data.toString(),
write: (data) => {
python.stdin.cork();
python.stdin.write(data);
python.stdin.end();
python.stdin.uncork();
},
});
}
});
python.stderr.on("data", (data) => {
stderr.push(data.toString());
if (Array.isArray(on) && typeof on[2] == "function") {
on[2]({
data: data.toString(),
write: (data) => {
python.stdin.cork();
python.stdin.write(data);
python.stdin.end();
python.stdin.uncork();
},
});
}
});
python.on("close", (code) => {
res({ code, stderr, stdout });
});
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment