经过一段时间的挣扎,我想出了代码
import discord
import os
import subprocess as sub
import psutil
client = discord.Client()
my_path = os.getcwd()
program_instance = False
currently_installed = os.path.isdir("web-application")
def run_command(command):
value = sub.Popen(command, stdout = sub.PIPE, stderr = sub.PIPE)
return value.communicate()
def kill():
global program_instance
if not program_instance:
return "Program instance not initiated";
process = psutil.Process(program_instance.pid)
for proc in process.children(recursive = True):
proc.kill()
process.kill()
program_instance = False
return "Instance Killed"
def delete_if_exists():
global currently_installed
kill()
if currently_installed:
os.system("rmdir /S /Q web-application")
while currently_installed:
currently_installed = os.path.isdir("web-application")
def download_from_git():
#pull from git
global currently_installed
kill()
delete_if_exists()
instance = sub.Popen("git clone LINKTOWEBAPPLICATION")
instance.communicate()
currently_installed = True
return "Successfully downloaded"
def run(download = False):
global program_instance
folders = run_command("dir")
if not currently_installed or download:
download_from_git()
kill()
path = my_path+"\\web-application"
#installing values in pipenv
install_command_instance = sub.Popen("pipenv install", cwd = path)
install_command_instance.communicate()
program_instance = sub.Popen("pipenv run app.py", cwd = path)
return "App Running"
@client.event
async def on_ready():
print("Gitty woke")
@client.event
async def on_message(message):
if message.author.bot or not message.channel.id == MYDISCORDUSERID:
return;
command = message.content
checker = lambda command_name: command == command_name
if checker("run"):
await message.channel.send(run())
if checker("kill"):
await message.channel.send(kill())
if checker("download"):
await message.channel.send(download_from_git())
if checker("run download"):
await message.channel.send(run(download = True))
if checker("ping"):
currently_installed = os.path.isdir("web-application")
await message.channel.send("Running:" + f"\n{program_instance=}, {currently_installed=}")
with open(".key", "r") as key:
client.run(key.read())这段代码最大的问题是扼杀正在运行的进程。我只想知道有没有更简单的方法来做这件事。如果我做出过复杂的选择。
编辑:这个机器人是为了从GitHub中提取一个回购程序,其中包含一个需要运行的web应用程序。我必须杀死这个应用程序的原因是我可以下载一个新版本并重新运行代码(因为这个网站的多个实例都是坏的)。问题是,当网站运行时,我还必须能够发送bot命令,因此必须将其作为单独的实例运行,这样bot才不会“阻塞”运行站点,并且仍然可以接受输入。
发布于 2021-03-30 13:19:25
这取决于这一进程的性质和目的。
例如,您可以将您的流程安排为一个协同线,并取消使用Future.cancel:https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel执行它。
您的过程扼杀方法是积极和相当危险的,一些更多的上下文,你为什么要取消进程和过程的性质,将有助于提供答案。
https://codereview.stackexchange.com/questions/258822
复制相似问题