简体   繁体   中英

Executing Python Script from NodeJS/Express instance using a relative URL

I am developing a web app that relies on NodeJS and the Express module in which I am trying to run a Python script from an express route. What I would like to do is store the Python script in /public/scripts/test.py and refer to it using a relative URL such as /scripts/test.py so that Node doesn't need to know anything about the environment in which it is running.

I've attempted to execute the Python script both by using the python-shell module and by simply using Node's built-in ChildProcess . In both cases I'm running into the same issue – the path to the Python script seems to treated as being absolute and thus the script isn't executed, resulting in a file not found error.

How can I go about invoking a Python script with a relative URL? I'm rather new to web development, so I would not be surprised if I was simply misunderstanding the situation.

EDIT: As jfreind00 pointed out, process.cwd() can be used to identify the present working directory on top of which a URL to the script can be built. Worked like a charm.

Turning my comments into an answer so you can mark this question as resolved.

Invoking a program from node follows all the normally expected path rules. If you precede the path with a / , then the system looks in the root of the current directory volume. If you don't want node to know about your external directory structure, then set an environment variable for the location or path prefix for your python script and have the node script read that environment variable. Either way, node has to either know about the actual path, it has to be in the node current working directory or it has to be in the path and you have to run it with something that will search the path.

If you want to see what the current working directory is in your particular configuration, then you can use:

console.log(process.cwd());

to see what the current working directory is so you can see how to base your path on that.

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