【问题标题】:Python Running multiple processes simultaneouslyPython 同时运行多个进程
【发布时间】:2019-07-16 00:58:12
【问题描述】:

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

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

我正在尝试创建一个快速的不和谐机器人:

import subprocess
import discord

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

现在,这个 sn-p 会做我想做的事,它会调用 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 之后运行第二个命令的尝试,都会使机器人崩溃,并且我无法检索错误消息。我的想法是要么是我没有看到的不和谐库中的设计,要么我需要以某种方式合并多线程,尽管我不确定从哪里开始。

【问题讨论】:

  • 我认为最后一行应该有一个列表作为arg,即subprocess.call(['killall', 'top'])

标签: python multithreading subprocess discord discord.py


【解决方案1】:

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

【讨论】:

  • 问题是我不能让函数等待顶部命令终止,而是我需要它独立运行以便它可以被杀死。
猜你喜欢
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多