簡體   English   中英

通過 node.Js 子進程運行 Python 腳本

[英]Run Python scripts via node.Js child process

我一直在開發一個非常簡單的帶有一些路由的 node.Js 服務器。 我嘗試使用 Node Js child-process package 實現一個每次到達時都能夠運行 python(3.6) 腳本的路由。 問題是:當我嘗試這樣做時,使用正確的命令行參數運行我的腳本,沒有任何反應。

我已經嘗試運行一個簡單的命令,例如創建一個空文件或一個簡單的pwd ,一切正常。 其次,如下所示,在我的 python 腳本中,我正在使用logging python package 來跟蹤工作流程。 不幸的是,我的logfile.log是空的。 我還嘗試從 python 中取回 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 並在標准 output 中打印:什么都沒有。 腳本的路徑是正確的,所以我真的不知道手動執行腳本和 node.js 之間有什么區別。

Node.Js 代碼:

app.get('/trigger',(req, res) => {
        console.log('/trigger');
        console.log(__dirname + "/../scripts/launcher.py")
        var key = req.query['Key'];
        const spawn = require('child_process').spawn;
        const pythonProcess = spawn("python3.6", [__dirname + "/../scripts/launcher.py", key]);
        console.log("process started with pid : " + pythonProcess.pid);
        pythonProcess.stdout.on('data', (data) => {
                console.log("child stdout")
                console.log(`\n${data}`);
        });
        res.status(200).send()
})

Python代碼:


def init_logger():
    # create logger with 'spam_application'
    logger = logging.getLogger('spam_application')
    logger.setLevel(logging.DEBUG)

    # Load variable to env
    load_dotenv()

    # create file handler which logs even debug messages
    fh = logging.FileHandler(dir_path + '/logfile.log')
    fh.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter("%(asctime)s; %(levelname)s ; %(message)s",
                                  "%d-%m-%Y %H:%M:%S ")
    fh.setFormatter(formatter)  # add formatter to ch
    logger.addHandler(fh)  # add ch to logger
    return logger


def main():
    logger = init_logger()
    logger.info("logfile has been updated :D")

    # Downloading mail before processing it
    raw_mail = fetch_mail(sys.argv[1])
    mailer = MailManager(logger)
    if mailer.entry_point(raw_mail) == -1:
        logger.error("Sender Not Authorized")
        return -1
    uploader = Uploader(logger)
    uploader.initialize_warning_count()
    result = mailer.get_mailobj()
    uploader.entry_point(result)
    return 0

最后是 Node.js pm2 日志:

0|| 2019-09-23T12:29:55: /trigger
0|| 2019-09-23T12:29:55: my/path/to/script/launcher.py
0|| 2019-09-23T12:29:55: process started with pid : 19068

所以我有一個 PID,這意味着命令運行良好(我不確定)。 我希望能夠在 logfile.log 中包含 python 的日志(就像我手動測試時一樣)。 有了該日志,我將能夠知道發生了什么。

謝謝大家,如果您需要有關我的問題的更多信息,請發表評論或自由編輯。

環境:python3.6,Ubuntu EC2 實例中的節點 v8.10.0。

當您使用節點生成一個進程時,如果您想獲得 stdio output 您需要將其作為選項傳遞,因此請執行以下操作:

const pythonProcess = spawn("python3.6", [__dirname + "/../scripts/launcher.py", key], { stdio: 'inherit' });

檢查: https://nodejs.org/api/child_process.html#child_process_options_stdio

暫無
暫無

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

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