Child_Processes 从 javascript 节点 js 调用函数到 python 与导入中断

Child_Processes calling function from javascript node js to python breaking with imports

我正在为我的应用程序使用 node js 以及 react.

我正在尝试使用 child_process 从我的节点 js 代码调用 python 函数,使用 this post 来指导我。看起来很简单,直到我意识到 child_process 用于调用 python 脚本,而不是带有函数的主要方法。

我对 Python 比较陌生,如果我在这里和那里混淆了术语,请原谅我。下面是我的 python 文件的一个非常基本的版本:

import sys
# other imports 

def __main__():
     one = function_one()
     two = function_two()
     arr = [one, two]
     print(arr)
     sys.stdout.flush()

def function_one():
     # do stuff, pretend it returns 'hello'
def function_two():
     # do stuff, pretend it returns 'world'

if __name__ == '__main__':
     __main__()

最终结果应该是 ['hello', 'world'],但似乎我没有得到任何回报。如您所见,我正在打印 arr 并在之后刷新它,所以它应该可以工作。

我让它工作的唯一方法是我的文件看起来像这样:

import sys
print('hello world')
sys.stdout.flush()

如您所见,没有主要方法或附加功能。 这是有原因的还是我只是错误地实施了它?谢谢!

编辑:

在尝试了几种不同的方法后,我发现我的一些导入出现问题,例如 pandasseaborn。如果我删除那些特定的导入,它会起作用,即使我通过 if 语句调用 __main__ 也是如此。有什么想法吗?

您声明了一个名为 __main__ 的函数,但从未调用过它。我认为您已经将一些事情与已知模式混为一谈,该模式会在将脚本作为模块导入时阻止代码执行。此模式的正确实现如下所示:

import sys

def myMainFunction(argv):
    # the code here

if __name__ == "__main__":
    myMainFunction(sys.argv)

__name__ is a special variable Python。如果直接执行脚本,它会自动设置为 "__main__"。如果它是导入的,它将包含模块的名称。

回到你的问题。如果您不打算将该脚本作为模块导入,这是我在评论中建议的解决方案:

Node.js:

const spawn = require('child_process').spawn;
const pythonProcess = spawn('python', ['script.py']);

pythonProcess.stdout.on('data', (data) => {
    console.log(data.toString());
});

Python:

import sys

def function_one():
    return 'hello'
def function_two():
    return 'world'

one = function_one()
two = function_two()
arr = [one, two]
print(arr)
sys.stdout.flush()

所以,我的问题是在我的 spawn 中,python 指向版本 2.7,而不是 3.6.将解决导入问题。