Python和子流程输入管道 [英] Python and subprocess input piping

查看:89
本文介绍了Python和子流程输入管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动的小脚本,每半小时将一个命令馈入一个Java程序(游戏服务器管理器),就像用户在键入它一样.但是,在阅读了文档并进行了实验之后,我无法弄清楚如何获得两件事:

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)一个允许用户在终端窗口中键入命令的版本,它们将被发送到服务器管理器输入,就像全部保存"命令一样.

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)仍在运行的版本,但是将任何新输入发送到系统本身,从而不再需要第二个终端窗口.实际上,这是现在发生的一半,因为键入内容时没有视觉反馈,但是一旦程序结束,很明显终端已经收到了输入.例如,如果在程序运行时键入"dir",将显示目录内容列表.这不是出于实用,而是出于理解.

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.

这篇关于Python和子流程输入管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆