2012-05-22 1 views
3

내가 PyZMQ의 IOLoop 인스턴스를 사용할 때 이상한 시스템 동작을 데 : 기본적으로 이벤트 루프 파일에서 내용을 JSON 요청에 대한 12345 포트를 zmq을 수신하고, 읽고 ZMQ IOLoop 인스턴스 쓰기/읽기 워크 플로우

def main(): 
    context = zmq.Context() 
    s = context.socket(zmq.REP) 
    s.bind('tcp://*:12345') 
    stream = zmqstream.ZMQStream(s) 
    stream.on_recv(on_message) 

    io_loop = ioloop.IOLoop.instance() 
    io_loop.add_handler(some_file.fileno(), on_file_data_ready_read_and_then_write, io_loop.READ) 
    io_loop.add_timeout(time.time() + 10, another_handler) 
    io_loop.start() 

def on_file_data_ready_read_and_then_write(fd, events): 
    # Read content of the file and then write back 
    some_file.read() 
    print "Read content" 
    some_file.write("blah") 
    print "Wrote content" 

def on_message(msg): 
    # Do something... 
    pass 

if __name__=='__main__': 
    main() 

사용할 수있을 때 (그리고 그럴 때, 파일을 조작하고 그 파일을 다시 조작합니다. 기본적으로이 파일은이를 위해 만들어진 특수/proc/커널 모듈입니다).

모든 것이 잘 작동하지만, 어떤 이유로 나는 다음과 같은 참조 strace를 볼 때 :

... 
1. read(\23424) <--- Content read from file 
2. write("read content") 
3. write("Wrote content") 
4. POLLING 
5. write(\324324) # <---- THIS is the content that was sent using some_file.write() 
... 

을 그래서 파이썬 스크립트의 순서로 수행되지 않은 파일에 쓰기처럼 보이지만 그 파일에 대한 시스템 호출은 비록 2 행과 3 행 사이에서 행해져 야 했음에도 불구하고 폴링 후에 수행되었습니다.

아이디어가 있습니까?

답변

1

캐싱 문제가있는 것 같습니다. some_file이 object와 같은 파일이라면 명시 적으로 .flush()를 호출 할 수 있습니다. ZMQ Socket도 마찬가지로 효율성을 위해 메시지를 보관할 수 있습니다.

some_file 참조가 가비지 수집 될 때 파일의 내용이 플러시되고 있습니다. 추가

:

파이썬의 최신 버전 오픈으로 제공하는 컨텍스트 관리자 로직()

with open("my_file") as some_file: 
    some_file.write("blah") 

는 즉시이 상황을 종료로, some_file가 자동으로 플러시하고 종료됩니다를 사용합니다.

관련 문제