2016-08-31 4 views
1

Node.js에서 파이썬에 인수를 전달하려고 시도하고 있습니다 (child_process 스폰). 또한 Node.js 배열에 지정된 인수 중 하나를 사용하여 특정 Python 함수를 호출하려고합니다. test() 파이썬 함수를 호출한다 명령 줄 인수를 사용하여 파일에서 파이썬 함수 호출

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

이다.

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 lib/test.py test arg3 2

test, arg32은 명령 줄 인수 일 뿐이며 testtest() 함수를 호출해야합니다.이 함수는 arg3, 에 대한 인수는 2입니다.

답변

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

@ 란티 아무 문제 없어, 기꺼이 도와 드리겠습니다. – Avantol13

관련 문제