如何在不阻塞的情况下从控制台获取输入?

2024-05-08 18:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想发出一个命令,向文本频道或用户发送消息,消息应该在控制台中输入,但input()似乎“阻止了程序”。虽然我试着解决这个问题,但问题仍然存在没有解决。怎么解决我能做些什么来解决这个问题?你知道吗

简单代码如下:

import discord
import typing
from discord.ext import commands

class BasicCmd(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def test(self, ctx, *, receiver: typing.Union[discord.User, discord.TextChannel]):
        '''
        I want to get input from console
        but input() block the program.
        '''
        content = input('Enter something: ')
        await receiver.send(content)

def setup(client):
    client.add_cog(BasicCmd(client))

如果我使用线程:

import discord
import typing
import threading
from discord.ext import commands

class BasicCmd(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def test(self, ctx, *, receiver: typing.Union[discord.User, discord.TextChannel]):
        '''
        I want to do this command with threading to figure out  
        this problem,but the problem still remain unsolve.
        '''
        content = threading.Thread(target=input,args=('Enter something: ',)).start()
        await receiver.send(content)
        '''It will  raise an HTTPException(Cannot send an enpty message,and the bot also "block" by "input")'''

def setup(client):
    client.add_cog(BasicCmd(client))

我修改了我的程序,但输入仍然阻止我的程序。 代码(仅测试):

import discord
import typing
import queue
import threading
from discord.ext import commands

class BasicCmd(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def test(self, ctx):
        inputQueue = queue.Queue()

        inputThread = threading.Thread(target=_read_kbd_input, args=(inputQueue,), daemon=True)
        # It still remain "blocking"
        inputThread.start()

        while (True):
            if (inputQueue.qsize() > 0):
                input_str = inputQueue.get()
                print("input_str = {}".format(input_str))
                return

def _read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    a=True
    while a:
        input_str = input()
        inputQueue.put(input_str)
        a=False
def setup(client):
    client.add_cog(BasicCmd(client))


Tags: fromimportselfclienttypinginputdefcommand

热门问题