简体   繁体   中英

Running a python script from node and saving a file

So I am able to run a python script, however I am having trouble to actually have the python script save a file. Running the python script directly from the terminal works, however when spawning a node process it seems to fail silently (the file never saves, thus the node script fails). Could this be a permissions or location problem, since running the python script directly works?

I have been using python-shell to ease the process. My current API endpoint is something like this:

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');
            }
        });
    });
});

I have checked the location of the script in python with os.getcwd() and tried to run a sleep command to make sure there is enough time between the saving of the file and Node finding it, but to no avail.

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

Does anyone have any experience with this or know what I am doing wrong?

Turns out it was a location issue. The files were being saved to the root of the NodeJS script. I managed to bypass the issue by passing the __dirname from node into the python script and changing the current working directory like so:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM