为什么循环不能正常运行

时间:2012-03-17 07:45:42

标签: python windows

我不明白为什么循环不运行我的Python脚本。

import gtk, sys
from ctypes import *

PIPE_ACCESS_DUPLEX = 0x3
PIPE_TYPE_MESSAGE = 0x4
PIPE_READMODE_MESSAGE = 0x2
PIPE_WAIT = 0
PIPE_UNLIMITED_INSTANCES = 255
BUFSIZE = 9600
NMPWAIT_USE_DEFAULT_WAIT = 0
INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535

MESSAGE = "Default answer from server\0"
szPipename = "\\\\.\\pipe\\mynamedpipe"

def ReadWrite_ClientPipe_Thread(hPipe):
    chBuf = create_string_buffer(BUFSIZE)
    cbRead = c_ulong(0)
    while True:
        fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE, byref(cbRead), None)
        if ((fSuccess ==1) or (cbRead.value != 0)):
            messageArd = chBuf.value
            cbWritten = c_ulong(0)
            fSuccess = windll.kernel32.WriteFile(hPipe,c_char_p(MESSAGE), len(MESSAGE), byref(cbWritten), None )
    windll.kernel32.FlushFileBuffers(hPipe)
    windll.kernel32.DisconnectNamedPipe(hPipe)
    windll.kernel32.CloseHandle(hPipe)
    return 0

def main(): 
    THREADFUNC = CFUNCTYPE(c_int, c_int)
    thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
    while True:
        print "Print test" #This should be repeated
        hPipe = windll.kernel32.CreateNamedPipeA(szPipename,PIPE_ACCESS_DUPLEX,PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,PIPE_UNLIMITED_INSTANCES,BUFSIZE, BUFSIZE,NMPWAIT_USE_DEFAULT_WAIT,None)
        fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
        if ((fConnected == 0) and (windll.kernel32.GetLastError() == ERROR_PIPE_CONNECTED)):
            fConnected = 1

        if (fConnected == 1):
            dwThreadId = c_ulong(0)
            hThread = windll.kernel32.CreateThread(None, 0,thread_func, hPipe, 0, byref(dwThreadId))

    gtk.main() 

if __name__ == "__main__": 
    main()

这应该重复:

 print "Print test"

如果我更改def Main或删除Named Pipe脚本,循环将正常运行。

def main(): 
    while True:
        print "Print test" #This should be repeated
    gtk.main() 

有人可以帮我解决这个问题吗?谢谢

1 个答案:

答案 0 :(得分:0)

解决了问题。

循环不起作用,因为有两个并发运行的循环,多线程解决方案。在同一个地方运行两个循环