简体   繁体   English

Python同时运行多个进程

[英]Python Running multiple processes simultaneously

I hope this isn't a duplicate but I know I'm so close to figuring this out, I just can't quite get the last bit. 我希望这不是重复的,但是我知道我已经很接近解决这个问题了,我只是不太了解最后一点。

I have this issue in Python of running two functions simultaneously. 我在Python中同时运行两个函数时遇到了这个问题。 I need to run "top" (linux command) as well as execute each new command in parallel. 我需要运行“ top”(Linux命令)以及并行执行每个新命令。 Here is an example. 这是一个例子。

A quick discord bot I'm trying to whip up: 我正在尝试的一个快速的不和谐机器人:

import subprocess
import discord

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

Now, this snippet will do what I want, it'll call a child process of top and leave it running. 现在,此代码片段将执行我想要的操作,将其称为top的子进程并使其运行。 The problem is that I can't run another subprocess in this same way. 问题是我不能以相同的方式运行另一个子进程。 If I add this code: 如果我添加以下代码:

@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')

It's a simple example, but It's the same with any program that needs to be left running. 这是一个简单的示例,但是对于需要保持运行状态的任何程序都是一样的。

Any attempt to run the second command after already starting top, it will crash the bot and I'm not able to retrieve an error message. 在启动top之后运行第二个命令的任何尝试,都会使bot崩溃,并且我无法检索错误消息。 My thought is either it's a design within the discord library that I'm not seeing, or I need to incorporate multi-threading somehow, although I'm unsure of the best place to start. 我的想法是要么是我不曾看到的不和谐库中的设计,要么我不确定以何种方式合并多线程,尽管我不确定最好的起点。

There is a function to handle asynchronous subprocess in asyncio . asyncio有一个处理异步子流程的asyncio You may use this library because you are working on discord.py , so i recommend you to use it. 您可能会使用此库,因为您正在使用discord.py ,因此我建议您使用它。

Reference : https://docs.python.org/3/library/asyncio-subprocess.html 参考: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM