【问题标题】:Running a python script from node and saving a file从节点运行 python 脚本并保存文件
【发布时间】:2017-07-13 11:05:37
【问题描述】:

所以我可以运行 python 脚本,但是我无法让 python 脚本保存文件。直接从终端运行 python 脚本可以工作,但是在生成节点进程时,它似乎默默地失败(文件永远不会保存,因此节点脚本失败)。这可能是权限或位置问题,因为直接运行 python 脚本有效?

我一直在使用python-shell 来简化流程。我当前的 API 端点是这样的:

router.get('/patientsExport', (req, res) => {
    const options = {
        mode: 'text',
        scriptPath: __dirname,
    };
  PythonShell.run('patientsExport.py', options, err => {
        if (err) {
            logger.error(err);
            throw err;
        }
        const filePath = path.join(__dirname, 'patientsExport.xlsx');
        fs.exists(filePath, exists => {
            if (exists) {
                // Deliver the file
            } else {
                res.writeHead(400, { 'Content-Type': 'text/plain' });
                res.end('ERROR File does NOT Exists');
            }
        });
    });
});

我已经使用os.getcwd() 检查了python 中脚本的位置,并尝试运行sleep 命令以确保在保存文件和节点找到它之间有足够的时间,但无济于事。

wb.save(filename=dest_filename)
while not exists(dest_filename):
    sleep(1)

有没有人有这方面的经验或知道我做错了什么?

【问题讨论】:

    标签: python node.js shell save


    【解决方案1】:

    原来是位置问题。这些文件被保存到 NodeJS 脚本的根目录。我设法通过将__dirname 从节点传递到 python 脚本并更改当前工作目录来绕过这个问题,如下所示:

    Javascript:

    const options = {
            mode: 'text',
            scriptPath: __dirname,
            args: [__dirname],
        };
      PythonShell.run('patientsExport.py', options, err => ...
    

    Python:

    import sys
    from os import chdir
    
    chdir(sys.argv[1]) if sys.argv[1] else sys.exit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-09
      相关资源
      最近更新 更多