代码之家  ›  专栏  ›  技术社区  ›  LukeN

如何使其与Windows兼容?

  •  1
  • LukeN  · 技术社区  · 14 年前

    你好,斯塔克!

    我在将我的一个Python脚本Linux移植到Windows时遇到了一个小(大)问题。最棘手的是,我必须启动一个进程,将它的所有流重定向到我在脚本中读写的管道中。

    对于Linux,这是小菜一碟:

    server_startcmd = [
               "java", 
               "-Xmx%s" % self.java_heapmax, 
               "-Xms%s" % self.java_heapmin,
               "-jar",
               server_jar,
               "nogui"
            ]
    
    server = Popen(server_startcmd, stdout = PIPE, 
                                    stderr = PIPE, 
                                    stdin  = PIPE)
    
    outputs = [
         server_socket, # A listener socket that has been setup before
         server.stderr,
         server.stdout,
         sys.stdin # Because I also have to read and process this.
       ]
    
    clients = []
    
    while True:
         read_ready, write_ready, except_ready = select.select(outputs, [], [], 1.0)
    
         if read_ready == []:
            perform_idle_command() # important step
         else:
            for s in read_ready:
               if s == sys.stdin:
                  # Do stdin stuff
               elif s == server_socket:
                  # Accept client and add it to 'clients'
               elif s in clients:
                  # Got data from one of the clients
    

    我知道对于Windows,win32api模块中有win32pipe。问题是,找到这个API的资源非常困难,而我发现的并没有真正的帮助。

    if os.name == 'nt':
       import win32pipe
      (stdin, stdout) = win32pipe.popen4(" ".join(server_args))
    else:
       server = Popen(server_args,
         stdout = PIPE,
         stdin = PIPE,
         stderr = PIPE)
       outputs = [server.stderr, server.stdout, sys.stdin]
       stdin = server.stdin
    
    [...]
    
    while True:
       try:
          if os.name == 'nt':
             outready = [stdout]
          else:
             outready, inready, exceptready = select.select(outputs, [], [], 1.0)
       except:
          break
    

    stdout 下面是已启动的子进程的组合stdout和stderr win32pipe.popen4(...)

    纵火的问题是:

    • 为什么不呢? select() 对于windows版本?这样不行吗?
    • 选择() 那么,我如何实现必要的超时呢 选择() 提供(在这里显然不会像这样工作)

    1 回复  |  直到 14 年前
        1
  •  0
  •   mdk    14 年前

    我认为不能在管道上使用select()。