Python同时运行多个进程

2024-04-28 15:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望这不是一个重复,但我知道我已经很快弄明白了,我只是不太明白最后一点。在

我在Python中遇到了同时运行两个函数的问题。我需要运行“top”(linux命令)并并行执行每个新命令。这里有一个例子。在

我想挑起一个不和谐的机器人:

import subprocess
import discord

@client.event #Event listener
def on_message(message):
   if message.content.startswith('top'):
       subprocess.call(['top'])

现在,这个代码片段将执行我想要的,它将调用top的一个子进程,并让它继续运行。问题是我不能以同样的方式运行另一个子进程。如果我添加此代码:

^{pr2}$

这是一个简单的例子,但是对于任何需要保持运行的程序来说都是一样的。在

任何试图在已经启动top之后运行第二个命令的尝试,都会使bot崩溃,我无法检索到错误消息。我的想法是要么是我看不到的discord库中的一个设计,要么我需要以某种方式合并多线程,尽管我不确定从哪个地方开始。在


Tags: 函数代码import命令clienteventmessage进程
1条回答
网友
1楼 · 发布于 2024-04-28 15:44:56

asyncio中有一个处理异步子进程的函数。您可能会使用此库,因为您正在处理discord.py,所以我建议您使用它。在

{a1}

@client.event
def on_message(message):
    if message.content.startswith('top'):
        proc = await asyncio.create_subprocess_shell(
            'top',
            stdout=asyncio.subprocess.PIPE
            stderr=asyncio.subprocess.PIPE)
        stdout, stderr = await proc.communicate()

    if message.content.startswith('kill top'):
        proc = await asyncio.create_subprocess_shell(
            'killall top',
            stdout=asyncio.subprocess.PIPE
            stderr=asyncio.subprocess.PIPE)
        stdout, stderr = await proc.communicate()

相关问题 更多 >