【问题标题】:Pass function and arguments from node to python, using child_process使用 child_process 将函数和参数从节点传递到 python
【发布时间】:2020-11-07 17:27:32
【问题描述】:

我是 child_process 的新手,我想试验一下它的功能。

有什么方法可以使用 spawn 将函数和参数传递给 python 文件(或者 exec 或 execFile 是 spawn 无法做到的)?

我想做一些类似(伪代码)的事情

spawnORexecORexefile (python path/to/python/file function [argument1, argument2] ) 

或许

spawnORexecORexefile (python path/to/python/file function(argument1, argument2) ) 

请解释一下,也许可以举个例子,因为我是新手

我现在怎么样了?

在节点中

 var process = spawn('python', [path/to/pythonFile.py, 50, 60] );  

pythonFile.py

import sys 
import awesomeFile

hoodie = int(sys.argv[1])
shoe = int(sys.argv[2])

awesomeFile.doYourMagic().anotherThing(hoodie, shoe)

如你所见,我从节点发送数据到pythonFile,然后到awesomeFile,发送到特定函数

我想“切断中间人”并删除pythonFile并将数据从节点直接发送到awesomeFile文件,发送到特定函数。这就是我问的原因

谢谢

【问题讨论】:

    标签: python node.js child-process


    【解决方案1】:

    您可以使用python -c 'import foo; print foo.hello()'(来自https://stackoverflow.com/a/3987113/5666087)的形式从命令行运行特定的Python函数。

    将以下两个文件放在同一目录中,并使用node index.js 运行。您应该会看到以下输出:

    Hoodie: 10
    Shoe: 15
    

    awesomeFile.py

    def myfunc(hoodie, shoe):
        hoodie = int(hoodie)
        shoe = int(shoe)
        print("Hoodie:", hoodie)
        print("Shoe:", shoe)
    

    index.js

    const { spawn } = require('child_process');
    let hoodie = 10,
        shoe = 15;
    const result = spawn("python",
        ["-c", `import awesomeFile; awesomeFile.myfunc(${hoodie}, ${shoe})`])
    result.stdout.pipe(process.stdout)
    

    【讨论】:

    • 坏消息。我对其进行了测试,无论我如何在节点中使用 spawn 部分的语法,我都会收到错误,生成代码 1 退出,`未捕获的致命异常 - 存在未捕获的异常,并且它不是由域或 uncaughtException 处理的事件处理程序。 ` .我在这里错过了什么?
    • 如果我打开一个 cmd 并 cd 到一个包含 python 文件的文件夹并尝试执行 python -c 'import test ; test.myFunc()' 我得到 ` File "", line 1 'import ^ SyntaxError: EOL while scanning字符串文字`
    • 可能是语法问题。您构建 spawn 的方式可能比 spawn 更适合 exec,因为您的语法更接近 shell 语法。也许spawn 完全需要另一种语法或其他代码
    • 你在windows上吗?您可以尝试使用双引号吗? python -c "import test ; test.myFunc()".
    • 是的,我在 Windows 上。等等,这对于不同的操作系统来说不是全局的吗?无论如何,我试过了,在 result.on('exit' 期间,我得到了退出代码 2 Unused (reserved by Bash for builtin misuse)
    【解决方案2】:

    您可以将要调用的所有相关函数分组到类中,并从映射到类函数的类中创建一个字典。您可以直接调用awesome.py 而无需中间的index.py。你可以用你的方法扩展类AwesomeFile

    以下程序将接受用户输入 -

    1. 运行哪个 python 文件
    2. 运行哪个方法
    3. 方法参数
    4. 参数数量不匹配
    5. 如果给出未知方法怎么办

    awesomeFile.py

    import sys
    
    class AwesomeFile:
    
        def __init__(self):
            pass
    
        def doYourMagic(self):
            return self
        
        def anotherThing(self, hoodie, shoe):
            print(int(hoodie))
            print(int(shoe))
    
    awesomeFile = AwesomeFile()
    methods = {m:getattr(awesomeFile, m) for m in dir(AwesomeFile) if not m.startswith('__')}
    
    def run():
        method_name = sys.argv[1]
        if method_name not in methods:
            print(f"Unknown Method {method_name}")
            return
        methodArgCount = methods[method_name].__code__.co_argcount
        if methodArgCount - 1 != len(sys.argv[2:]):
            print(f"Method {method_name} takes {methodArgCount - 1} arguments but you have given {len(sys.argv[2:])}")
            return
        
        methods[method_name](*sys.argv[2:])
    
    if __name__ == "__main__":
        run()
    

    index.js

    注意** - 您将安装 prompt - npm i prompt

    'use strict';
    var prompt = require('prompt');
    const { spawn } = require( 'child_process' );
    
    var prompt_attributes = [
        {        
            name: 'pythonFilePath'
        },
        {   
            name: 'cmdLineArgs'
        }
    ];
    
    prompt.start();
    
    prompt.get(prompt_attributes, function (err, result) {
        if (err) {
            console.log(err);
            return 1;
        }else {
            console.log('Command-line received data:');
            var filePath = result.pythonFilePath;
            var cmdLineArgs = result.cmdLineArgs;
            var args = cmdLineArgs.split(" ");
            args.unshift(filePath);
            
            const pythonProgram = spawn( 'python' , args);
    
            pythonProgram.stdout.on( 'data', data => {
                console.log( `stdout:\n\n ${data}` );
            } );
    
            pythonProgram.stderr.on( 'data', data => {
                console.log( `stderr: ${data.data}` );
            } );
    
            pythonProgram.on( 'close', code => {
                console.log( `child process exited with code ${code}` );
            } );
        
        }
    });
    

    运行程序 -

    I/O:

    参数不匹配 -

    prompt: Python File Path. Give absolute or relative path: ../python_files/awesomeFile.py # python file can be any location in the system
    prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2):  anotherThing 1
    Command-line received data:
    stdout:
    
     Method anotherThing takes 2 arguments but you have given 1
    
    child process exited with code 0
    

    未找到函数

    prompt: Python File Path. Give absolute or relative path:  ../python_files/awesomeFile.py
    prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2):  helloworld 1 2
    Command-line received data:
    stdout:
    
     Unknown Method helloworld
    
    child process exited with code 0
    

    成功案例:

    prompt: Python File Path. Give absolute or relative path:  ../python_files/awesomeFile.py
    prompt: Command Line Arguments. Format = func_name arguments_list (Ex addFunc 1 2):  anotherThing 50 60
    Command-line received data:
    stdout:
    
     50
    60
    
    child process exited with code 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 2017-08-13
      • 2019-01-13
      • 2018-01-15
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多