亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用子進程來控制我的世界服務器

使用子進程來控制我的世界服務器

紅顏莎娜 2022-09-13 17:38:35
我在我的PC上為朋友運行了許多經過修改的Minecraft服務器,我正在嘗試構建一個程序,使啟動它們并向它們發送命令變得更加容易。我使用bat文件啟動服務器,并且能夠毫無問題地做到這一點,但我不確定如何通過控制臺向服務器添加命令的功能。subprocess我想過使用,在交互式控制臺中,它工作得很好。問題是,當我將其添加到代碼中時,它會在服務器啟動之前執行stop命令,因此服務器永遠不會停止。我嘗試過在單獨的函數中執行此操作,但這也不起作用。stdin.write()這是我到目前為止的代碼:類文件:import subprocessclass Server:    def __init__(self, server_start_bat, dir):        self.server_start_bat = server_start_bat        self.dir =dir    def start_server(self):        server = subprocess.Popen(self.server_start_bat, cwd=self.dir, shell=True, stdin=subprocess.PIPE, text=True)        server.communicate()    def stop_server(self):        server = subprocess.Popen(self.server_start_bat, cwd=self.dir, shell=True, stdin=subprocess.PIPE, text=True)        server.stdin.write('stop\n')    def command(self, command):        server = subprocess.Popen(self.server_start_bat, cwd=self.dir, shell=True, stdin=subprocess.PIPE, text=True)        self.command = command        server.stdin.write(f'{self.command}\n')簡單的GUI我運行了它:from tkinter import *import Serversserver = Servers.Server('path\\to\\bat\\file\\batfile.bat', 'dir\\to\\run\\command\\in')main = Tk()main.title('Server Commander')server_title = Label(main, text="server, hosted on port ")server_title.pack()server_start = Button(main, text='Start', command=server.start_server)server_start.pack()server_stop = Button(main, text='Stop', command=server.stop_server)server_stop.pack()main.mainloop()
查看完整描述

1 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

我認為有兩個問題:

  1. stop_server并且每個子進程都啟動一個新的子進程,這只能在 中完成。commandstart_server

  2. start_server在子進程完成之前使用哪些塊,從而防止程序在運行時向服務器發送任何其他命令。server.communicate()

相反

  • start_server應創建子進程,然后將其存儲在可由 和 訪問的變量中,stop_servercommand

  • server.communicate應在 中完成。stop_server

stop_server也只是 的一個特例。command

import subprocess


class Server:

    def __init__(self, server_start_bat, dir):

        self.server_start_bat = server_start_bat

        self.dir = dir


    def start_server(self):

        self.server = subprocess.Popen(self.server_start_bat, cwd=self.dir, shell=True, stdin=subprocess.PIPE, text=True)


    def stop_server(self):

        self.command('stop')

        self.server.communicate()


    def command(self, command):

        self.server.stdin.write(f'{command}\n')


查看完整回答
反對 回復 2022-09-13
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號