2016-08-31 21 views
1

Node.jsからPythonに引数を渡して、child_process spawnで渡そうとしています。また、Node.js配列で指定した引数の1つを使用して、特定のPython関数を呼び出すこともできます。コマンドライン引数を使ってファイル内のPython関数を呼び出す

test.js

'use strict'; 

const path = require('path'); 
const spawn = require('child_process').spawn; 

const exec = (file, fnCall, argv1, argv2) => { 
    const py = spawn('python', [path.join(__dirname, file), fnCall, argv1, argv2]); 
    py.stdout.on('data', (chunk) => { 
    const textChunk = chunk.toString('utf8'); // buffer to string 
    const array = textChunk.split(', '); 
    console.log(array); 
    }); 
}; 
exec('lib/test.py', 'test', 'argument1', 'argument2'.length - 2); // => [ 'argument1', '7' ] 
exec('lib/test.py', 'test', 'arg3', 'arg4'.length - 2); // => [ 'arg3', '2' ] 

ここでは二番目の引数は、test() Pythonの関数を呼び出すべきか、testです。

lib/test.pyは:

import sys 

def test(): 
    first_arg = sys.argv[2] 
    second_arg = sys.argv[3] 
    data = first_arg + ", " + second_arg 
    print(data, end="") 

sys.stdout.flush() 

私は、コマンドラインからの任意のNode.jsことなく、このPythonのファイルを実行しようとすると、実行は次のようになります。

$ python lib/test.py test arg3 2

testarg3 、および2はコマンドライン引数ですが、testtest()関数を呼び出す必要があります。この関数はarg3,引数はprint()です。

答えて

3

argparseを使用してコマンドライン引数を解析することをお勧めします。次に、evalを使用して、入力から実際の関数を取得することができます。

import argparse 

def main(): 
    # Parse arguments from command line 
    parser = argparse.ArgumentParser() 

    # Set up required arguments this script 
    parser.add_argument('function', type=str, help='function to call') 
    parser.add_argument('first_arg', type=str, help='first argument') 
    parser.add_argument('second_arg', type=str, help='second argument') 

    # Parse the given arguments 
    args = parser.parse_args() 

    # Get the function based on the command line argument and 
    # call it with the other two command line arguments as 
    # function arguments 
    eval(args.function)(args.first_arg, args.second_arg) 

def test(first_arg, second_arg): 
    print(first_arg) 
    print(second_arg) 

if __name__ == '__main__': 
    main() 
+1

ありがとうございます!完璧に動作します! – Lanti

+1

@Lanti問題はありません、喜んで助けてください – Avantol13

関連する問題