python-3.x - 使用 python 控制 minecraft 服务器

标签 python-3.x server minecraft servermanager

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

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 在 minecraft 服务器运行的情况下保持打开状态。我不确定为什么会发生这种情况或问题是什么,我们将不胜感激。

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

最佳答案

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

另一方面,使用 subprocess.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"),您还可以使用打印函数的 file 可选参数,因此:

print(cmd, file=process.stdin)

将数据写入 process.stdin,格式与 print 正常相同,比如以换行符结尾,除非传递 end= 来覆盖它等。

关于python-3.x - 使用 python 控制 minecraft 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40750727/

相关文章:

lua - 窗口 :94:arguments must be the same length stand for? 是什么意思

java - 在我的Minecraft服务器上,我的插件未加载

python-3.x - 不同特征的不同内核 - scikit-learn SVM

python-3.x - 无论如何,您是否可以检查 Azure CLI 在后台执行哪些 API 调用?

python - 如何为每个索引值添加差异行?

ruby-on-rails - 重新安装 rvm/rails 后无法启动 rails 服务器

php - 数据库和 Web 服务器位于不同的提供商机器上

python-3.x - Tkinter:如何使 tkinter 文本小部件更新?

windows - 如何在 Windows 32 位上运行 Redis?

java - Minecraft Bukkit Activity