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

python和子进程输入管道

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

    我有一个小脚本启动,每半个小时,向一个Java程序(游戏服务器管理器)输入命令,就像用户正在键入它一样。但是,在阅读了文档并进行了实验之后,我不知道如何获得以下两个方面:

    1)允许用户在终端windoe中键入命令的版本,它们将像“全部保存”命令一样发送到服务器管理器输入。

    2)保持运行但向系统本身发送任何新输入的版本,不需要第二个终端窗口。这一次实际上是现在的一半,因为当某个东西被输入时,没有视觉反馈,但是一旦程序结束,很明显终端已经收到了输入。例如,如果在程序运行时键入了“dir”,则会出现目录内容列表。这一条更多是为了理解而不是实际。

    谢谢你的帮助。脚本如下:

    from time import sleep
    import sys,os
    import subprocess
    
    
    #  Launches the server with specified parameters, waits however
    #  long is specified in saveInterval, then saves the map.
    
    
    #  Edit the value after "saveInterval =" to desired number of minutes.
    #  Default is 30
    
    saveInterval = 30
    
    #  Start the server.  Substitute the launch command with whatever you please.
    p = subprocess.Popen('java -Xmx1024M -Xms1024M -jar minecraft_server.jar',
                         shell=False,
                         stdin=subprocess.PIPE);
    
    while(True):
    
        sleep(saveInterval*60)
    
        #  Comment out these two lines if you want the save to happen silently.
        p.stdin.write("say Backing up map...\n")
        p.stdin.flush()
    
        #  Stop all other saves to prevent corruption.
        p.stdin.write("save-off\n")
        p.stdin.flush()
        sleep(1)
    
        #  Perform save
        p.stdin.write("save-all\n")
        p.stdin.flush()
        sleep(10)
    
        #  Allow other saves again.
        p.stdin.write("save-on\n")
        p.stdin.flush()
    
    3 回复  |  直到 14 年前
        2
  •  1
  •   kanaka    14 年前
        3
  •  1
  •   Paulo Scardine    14 年前