2017-02-25 5 views
3

노드 모듈 PythonShell을 사용하여 Python과 통신하는 nw.js 응용 프로그램을 만들려고합니다.노드의 PythonShell (nwjs)

내가 겪고있는 문제는 stdin을 닫지 않으면 콘솔에 아무 것도 기록되지 않는다는 것입니다. 그러나 스트림을 열어서 Python 스크립트에 여러 명령을 보내고 Python의 상태를 저장할 수 있도록하고 싶습니다. 여기

내 스크립트입니다 :

script.py

import sys 

def main(): 
    command = sys.stdin.readlines() # unused for now 
    sys.stdout.write("HELLO WORLD") 
    sys.stdout.flush() 

if __name__ == '__main__': 
    main() 

main.js이 시점에서

var PythonShell = require('python-shell'); 
var pyshell = new PythonShell('script.py'); 

pyshell.on('message', function (message) { 
    console.log(message); 
}); 

pyshell.send('hello'); 

아무 일도 발생하지 않습니다.

pyshell.end()을 입력하면 HELLO WORLD이 콘솔에 출력됩니다. 그런데 더 이상 pyshell.send 명령을 사용할 수 없습니다.

어떻게 파이썬 자식 프로세스가 실행 중이며 입력을 기다리고 있지만 모든 출력을 JS로 파이프 할 수 있습니까?

+0

같은 문제가있는 pythonshell 대신에'child_process.spawn' 모듈을 직접 사용해 보았습니다. – Jeff

답변

2

문제의 몇 :

  • 사용 sys.stdin.readline() 대신 sys.stdin.readlines(). 그렇지 않으면, 파이썬은 입력 스트림을 끝내기를 계속 기다린다. ^D 신호를 보내서 입력의 끝을 종료 할 수 있어야하지만 그게 효과가 없습니다.

  • 또한

중요한 (아래 파이썬 코드 참조), 오픈 스트림을 유지 루프에서 명령 라인 입력을 감싸는 :

  • 입력 자동 \n 추가되지만 출력하지 아니. 어떠한 이유로 든 출력에는 \nsys.stdout.flush()이 모두 필요합니다. 하나 또는 다른 사람이 그것을 자르지 않을 것입니다.

  • 파이썬 쉘이 파이썬 코드를 캐시하는 것처럼 보입니다. 따라서 파이썬 파일을 변경하면 nwjs 응용 프로그램을 다시 시작해야 적용됩니다.

    script.py

    import sys 
    
    def main(): 
        while True: 
         command = sys.stdin.readline() 
         command = command.split('\n')[0] 
         if command == "hello": 
          sys.stdout.write("You said hello!\n") 
         elif command == "goodbye": 
          sys.stdout.write("You said goodbye!\n") 
         else: 
          sys.stdout.write("Sorry, I didn't understand that.\n") 
         sys.stdout.flush() 
    
    if __name__ == '__main__': 
        main() 
    

    main.js 이제

    var PythonShell = require('python-shell'); 
    var pyshell = new PythonShell('script.py'); 
    
    pyshell.on('message', function (message) { 
        console.log(message); 
    }); 
    
    pyshell.send('hello'); 
    

    , pyshell.send("hello")pyshell.send("goodbye"), 또는 pyshell.send("garbage")를 사용하고 나타납니다 여기에

은 전체 샘플의 작동 코드 JS 콘솔의 즉각적인 응답!