[英]Python and subprocess input piping
我有一个小脚本启动,并且每半小时向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()
用select((sys.stdin, ), (), (), saveInterval*60)
调用替换你的sleep()
- 它将具有相同的超时但是在stdin上监听用户命令。 如果select
表示您有输入,请从sys.stdin中读取一行并将其提供给您的进程。 当select
指示超时时,执行您现在正在执行的“保存”命令。
它不会完全解决您的问题,但您可能会发现python的cmd模块很有用。 这是一种轻松实现可扩展命令行循环(通常称为REPL)的方法。
您可以使用屏幕运行程序,然后您可以将输入发送到特定的屏幕会话而不是直接发送到程序(如果您在Windows中只是安装cygwin)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.