运行 Python 个脚本通过 node.Js 个子进程

Run Python scripts via node.Js child process

我一直在开发一个非常简单的 node.Js 服务器,其中包含一些路由。我尝试使用 Node Js child-process 包实现一种每次到达时都能够 运行 一个 python(3.6) 脚本的路由。问题是:当我尝试这样做时,运行使用正确的命令行参数设置我的脚本,没有任何反应。

我已经尝试过 运行 一个简单的命令,比如创建一个空文件或只是一个简单的 pwd 一切正常。其次,正如您在下面看到的,在我的 python 脚本中,我使用 logging python 包来跟踪工作流程。不幸的是,我的 logfile.log 是空的。我还尝试从 python 取回流并在标准输出中打印:无。脚本的路径是正确的,所以我真的不知道我手动执行脚本和 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,这意味着命令 运行ning 很好(我不确定)。我希望能够在 logfile.log 中包含 python 的日志(就像我手动测试时一样)。有了那个日志,我就能知道到底发生了什么。

谢谢大家,如果您需要有关我的问题的更多信息,请发表评论或自由编辑。

环境:python3.6,Ubuntu EC2 实例中的节点 v8.10.0。

当你用节点生成一个进程时,如果你想获得 stdio 输出,你需要将它作为一个选项传递,所以做这样的事情:

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

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