简体   繁体   English

使用相对URL从NodeJS / Express实例执行Python脚本

[英]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. 我正在开发一个依赖NodeJS和Express模块​​的Web应用程序,其中我试图从Express路由运行Python脚本。 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. 我想做的就是将Python脚本存储在/public/scripts/test.py并使用/scripts/test.py类的相对URL进行引用,以便Node不需要了解有关环境的任何信息。它正在运行。

I've attempted to execute the Python script both by using the python-shell module and by simply using Node's built-in ChildProcess . 我试图通过使用python-shell模块和仅使用Node的内置ChildProcess来执行Python脚本。 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. 在这两种情况下,我都遇到相同的问题– Python脚本的路径似乎被视为绝对路径,因此该脚本未执行,从而导致找不到文件错误。

How can I go about invoking a Python script with a relative URL? 如何使用相对URL调用Python脚本? I'm rather new to web development, so I would not be surprised if I was simply misunderstanding the situation. 我是Web开发的新手,所以如果我只是误解了情况,我不会感到惊讶。

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. 编辑:正如jfreind00所指出的,process.cwd()可以用于标识当前的工作目录,在该目录的基础上可以建立脚本的URL。 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. 如果您不希望节点知道您的外部目录结构,请为python脚本的位置或路径前缀设置一个环境变量,并让节点脚本读取该环境变量。 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. 查看当前的工作目录是什么,以便您可以查看如何基于该目录创建路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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