简体   繁体   中英

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. I need to run "top" (linux command) as well as execute each new command in parallel. 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. 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. 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 . You may use this library because you are working on discord.py , so i recommend you to use it.

Reference : 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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