2

我已经为此进行了很多搜索,但尚未找到明确的解决方案。我发现的最接近的是:

import shutil
from os.path import join
import os
import time
import sys

minecraft_dir = ('server diectory')
world_dir = ('server world driectory')

def server_command(cmd):
    os.system('screen -S  -X stuff "{}\015"'.format(cmd))

on = "1"

while True:
    command=input()
    command=command.lower()
    if on == "1":
        if command==("start"):
            os.chdir(minecraft_dir)
            os.system('"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java')
            print("Server started.")
            on = "0"
    else:
        server_command(command)

当我启动这个程序并输入“开始”时,CMD 会闪烁并立即关闭。相反,我希望 CMD 保持打开状态,同时运行我的世界服务器。我不确定为什么会发生这种情况或问题是什么,任何帮助将不胜感激。

ps 我已根据需要对其进行了编辑(例如删除了不必要的备份脚本),但它以前不起作用。原文链接为:https ://github.com/tschuy/minecraft-server-control

4

2 回答 2

5

os.system将简单地运行该命令,然后返回到您的 python 脚本,而无法与它进一步通信。

另一方面 usingsubprocess.Popen使您可以在进程运行时访问它,包括写入它.stdin是您将数据发送到服务器的方式:

def server_command(cmd):
    process.stdin.write(cmd+"\n") #just write the command to the input stream
process = None
executable = '"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java'
while True:
    command=input()
    command=command.lower()
    if process is not None:
        if command==("start"):
            os.chdir(minecraft_dir)
            process = subprocess.Popen(executable, stdin=subprocess.PIPE)
            print("Server started.")
    else:
        server_command(command)

你也可以通过stdout=subprocess.PIPE,这样你也可以读取它的输出并stderr=subprocess.PIPE从它的错误流中读取(如果有的话)

除了process.stdin.write(cmd+"\n")你也可以使用fileprint 函数的可选参数,所以这个:

print(cmd, file=process.stdin)

将数据写入 process.stdin 格式,格式与 print 通常一样,例如以换行符结尾,除非传递end=以覆盖它等。

于 2016-12-22T14:55:14.303 回答
0

以上两个答案在我尝试过的环境中都不起作用。

我认为最好的方法是使用 RCON,而不是向窗口发送密钥。

RCON 是游戏用来运行命令的协议。

许多 python 库支持 Minecraft RCON,默认 server.properties 文件有一个 RCON 选项。

我们将使用 python 模块:MCRON

安装它。它适用于 Windows、Mac、Linux。

类型:

pip install mcrcon

让我们配置您的服务器以允许 RCON。

在 server.properties 中,找到“enable-rcon”行并使其如下所示:

enable-rcon=true

重新启动并停止您的服务器。找到“rcon.password”行并将其设置为您能记住的任何密码。

您可以将端口默认设置为 25575。

现在,打开你的终端并输入:

mcron localhost

或者你的服务器ip。

系统将提示您输入您设置的密码。然后你可以运行命令并得到结果。

但是我们用 python 来做这件事,而不是 PYPI MCRON 脚本——所以这样做。

from mcrcon import MCRcon as r
with r('localhost', 'insertyourpasswordhere') as mcr:
    resp = mcr.command('/list')
print(resp) #there are 0/20 players online: - This will be different for you.
于 2021-04-09T15:20:24.237 回答