簡體   English   中英

如果腳本有無限循環,則停止 python-shell

[英]Stopping python-shell if a script has an endless loop

我正在開發一個 Node.js 應用程序,它接受提交的 Python 代碼並在這些提交上運行測試套件。 我一直在使用python-shell package運行Node.js內的Python,當提交失敗或者通過測試用例時,一切正常。 當 Python 腳本包含無限循環時,就會出現問題。 在這種情況下,python-shell 實例永遠不會終止。
我檢查了一些堆棧溢出已經問過的問題,例如How to set a time limit to run asynchronous function in node.js? , 從 NodeJS 啟動和停止 Python 腳本? 我如何停止 PythonShell但似乎沒有什么可以處理腳本中的無限循環。 如果 promise 在幾秒鍾內沒有解決,我想終止我的 judgeRoutine() 。 我嘗試使用超時並承諾解決問題,但到目前為止無濟於事。 我包括我擁有的代碼:

//judge.js
const {PythonShell} = require('python-shell')

const fs = require('fs');

function judgeRoutine(){
    let output=""
    return new Promise(function(resolve, reject){
        PythonShell.run('./test.py', null,function(err, result){
            if(err){
                return err
            }
            output = result[1]
            console.log(output)

            //perform DB operations based on output value

            return resolve(output)
        })
        setTimeout(function(){if (output===""){
            return reject(new Error("Time out"));
        }
        else{
            resolve(output)
        }} ,1000)
    })
    .catch(err => console.log(err))
}

function runJudge(){
    new Promise(function(resolve, reject){
        //copy scripts into the folder
        //solution2.py contains an endless loop
        fs.copyFile('./submissions/solution2.py', './solution.py', (err) => {
            if (err) throw err;
            console.log('File was copied to destination');
        });

        fs.copyFile('./tests/test35345.py', './test.py', (err) => {
            if (err) throw err;
            console.log('File was copied to destination');
        })    
    }).then(judgeRoutine()).then(value => console.log("resolve value", value)).catch(err=> {if (err.name==="Time out"){
        reject("Time out")
    }})
}

module.exports={runJudge}

我很樂意得到任何建議。

我在 Node.js 服務器上運行的 python 腳本中包含了我用來停止無限循環的代碼片段。

在這里,我只是創建了一個簡單的 promise 來異步運行 python 腳本,以免阻塞主線程。 但我還添加了一個 removeEventlistener function 它將在一定時間后停止運行 python 腳本。 您可以根據需要調整該值。

此外,您可能已經注意到我沒有使用任何第三方庫,而是使用了 Node.js 中內置的庫。無論如何,希望它能讓您了解如何停止 Node.js 中長時間運行的 python 腳本進程

const pythonPromise = () => {
  return new Promise((resolve, reject) => {
    const python = spawn("python", ["./script.py"]);

    const print = (data) => {
      console.log(data.length);
      console.log(data);
      resolve(data.toString());
    };
    python.stdout.on("data", print);

    setTimeout(() => {
      python.stdout.off("data", print);
      resolve("Infinite code detected");
    }, 5000);

    python.stderr.on("data", (data) => {
      reject(data.toString());
    });
  });
};

async function runCode() {
  const value = await pythonPromise().catch(console.log);
  console.log(value);
} 

runCode()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM