Python同时运行多个进程

时间:2019-02-22 00:54:09

标签: python multithreading subprocess discord discord.py

我希望这不是重复的,但是我知道我已经很接近解决这个问题了,我只是无法完全了解最后一点。

我在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')

这是一个简单的示例,但是对于任何需要保持运行状态的程序来说,都是相同的。

任何尝试在启动top之后运行第二条命令的操作,都会使bot崩溃,并且我无法检索到错误消息。我的想法是要么是我不曾看到的不和谐库中的一个设计,要么我不确定以什么为最佳起点。

1 个答案:

答案 0 :(得分: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()