开发者

Python and subprocess input piping

I have a small script that launches and, every half hour, feeds a command to a java program (game server manager) as if the user was typing it. However, after reading documentation and experimenting, I can't figure out how I can get two things:

1) A开发者_运维问答 version which allows the user to type commands into the terminal windoe and they will be sent to the server manager input just as the "save-all" command is.

2) A version which remains running, but sends any new input to the system itself, removing the need for a second terminal window. This one is actually half-happening right now as when something is typed, there is no visual feedback, but once the program is ended, it's clear the terminal has received the input. For example, a list of directory contents will be there if "dir" was typed while the program was running. This one is more for understanding than practicality.

Thanks for the help. Here's the script:

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()


Replace your sleep() with a call to select((sys.stdin, ), (), (), saveInterval*60) -- that will have the same timeout but listens on stdin for user commands. When select says you have input, read a line from sys.stdin and feed it to your process. When select indicates a timeout, perform the "save" command that you're doing now.


It won't completely solve your problem, but you might find python's cmd module useful. It's a way of easily implementing an extensible command line loop (often called a REPL).


You can run the program using screen, then you can send the input to the specific screen session instead of to the program directly (if you are in Windows just install cygwin).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜