【问题标题】:Python and subprocess input pipingPython 和子进程输入管道
【发布时间】:2010-11-02 18:27:17
【问题描述】:

我有一个启动的小脚本,每半小时向 java 程序(游戏服务器管理器)提供一个命令,就好像用户正在键入它一样。但是,在阅读文档和实验之后,我无法弄清楚如何获得两件事:

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

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

【问题讨论】:

    标签: python pipe subprocess popen


    【解决方案1】:

    将您的sleep() 替换为对select((sys.stdin, ), (), (), saveInterval*60) 的调用——这将具有相同的超时时间,但会在标准输入上侦听用户命令。当select 说您有输入时,从 sys.stdin 中读取一行并将其提供给您的进程。当select 指示超时时,执行您现在正在执行的“保存”命令。

    【讨论】:

    • 太棒了,我没听说过这个。谢谢。
    • 作为一个警告——你没有提到你在什么平台上——select 可能无法在 win32 上正常工作。我只熟悉 *nix。
    【解决方案2】:

    它不会完全解决您的问题,但您可能会发现 python 的 cmd 模块很有用。这是一种轻松实现可扩展命令行循环(通常称为 REPL)的方法。

    【讨论】:

    • 我可能会尝试重新调整一下,在这种情况下 cmd 可能真的很有用。感谢您的建议。
    【解决方案3】:

    您可以使用屏幕运行程序,然后您可以将输入发送到特定的屏幕会话而不是直接发送到程序(如果您在 Windows 中只需安装 cygwin)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 2015-10-24
      • 2015-05-07
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多