![](/img/trans.png)
[英]How to get the exit code from a file ran using javascript child_process.execFile
[英]Is there a way to get 'live' output lines from a python script spawned by child_process.execFile without flushing stdout every time?
我正在嘗試將 ('永無止境') python 腳本放入標准輸出中。 但目前我的代碼只會在 python 進程退出時將某些內容記錄到控制台。 有沒有辦法逐行獲取 python 腳本的“實時”output?
spawn_child.js:
let execFile = require("child_process").execFile;
var child = execFile("python3", ["PATH_TO_FILE"]);
child.stdout.on("data", data=>{
console.log(data.toString());
});
child.stderr.on("data", data=>{
console.log(data.toString());
});
child.on("exit", code=>{
console.log("Child exited with code "+code);
});
python 文件:
from time import sleep
while True:
sleep(3)
print("test")
編輯:它在使用 nodejs 腳本而不是 python 腳本時有效
將 python 腳本更改為
import time
import sys
while True:
time.sleep(1)
print("test")
sys.stdout.flush()
並增加子進程的緩沖區大小
const child = execFile("python", ["./runner.py"], {
detached: true,
maxBuffer: 10 * 1024 * 1024 * 1024
});
或者你可以在不使用python-shell刷新到標准輸出的情況下做到這一點
const { PythonShell } = require('python-shell');
let pyshell = new PythonShell('runner.py');
pyshell.on('message', function (message) {
console.log(message);
});
pyshell.end(function (err, code, signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
使用spawn而不是 execFile,不要忘記選項shell
和stdio
。
const spawn = require("child_process").spawn;
const child = spawn("python3", ["file.py"], {shell: true, stdio: 'inherit'});
child.on('data', function(data) {
console.log(data);
});
child.on('close', function(code) {
console.log('Child process exited with exit code '+code);
});
您還可以添加cwd
選項。
試圖在 NextJS 應用程序中實現類似的東西,並希望從我的 python 腳本中實時運行 output 並使用python-shell
有同樣的問題,當進程存在時它只給我 output 而我最終使用node-pty
而不是它作為預期的:
import { spawn } from "node-pty"
const pyProcess = spawn("python", ["path/to/python/script"], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
});
pyProcess.on('data', function (data: { toString: () => any; }) {
console.log(data.toString());
});
pyProcess.on('exit', (code: any) => {
console.log(`child process exited with code ${code}`);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.