Python同时运行多个进程

问题描述 投票:0回答:1

我希望这不是重复,但我知道我已经非常接近于解决这个问题,我不能完全理解这一点。

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

一个快速的不和谐机器人我正试图掀起:

import subprocess
import discord

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

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

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

   if message.content.startswith('kill top')
       subprocess.call('killall', 'top')

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

任何尝试在已经开始顶部之后运行第二个命令,它将使机器人崩溃并且我无法检索错误消息。我的想法要么是它在discord库中的设计,我没有看到,或者我需要以某种方式结合多线程,虽然我不确定最好的起点。

python multithreading subprocess discord discord.py
1个回答
0
投票

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

参考:https://docs.python.org/3/library/asyncio-subprocess.html

@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()
© www.soinside.com 2019 - 2024. All rights reserved.