【问题标题】:How to have Python accept multiple words as parameters?如何让 Python 接受多个单词作为参数?
【发布时间】:2020-07-20 14:56:01
【问题描述】:

这正是我试图开始工作的应用程序:我试图允许用户为“状态”参数输入多个单词。

即!setstatus 玩英雄联盟

显示“Playing League”而不是整个字符串。我明白为什么,但是如何格式化参数以接受多个单词作为参数?我什至可以这样做吗?

@bot.command() 
@commands.has_role('Bot Boss')
async def setstatus(ctx, action, status, url = None): 

    accepted_actions = ['playing', 'streaming', 'listening', 'watching']

    if action.lower() not in accepted_actions:
        await ctx.send("First parameter must be 'playing', 'streaming', 'listening', or 'watching'.")



    if action.lower() == 'playing':
        await bot.change_presence(activity = discord.Game(name = status))

    if action.lower() == 'streaming':
        await bot.change_presence(activity = discord.Streaming(name = status, url = url))

    if action.lower() == 'listening':
        await bot.change_presence(activity = discord.Activity(type=discord.ActivityType.listening, name=status))

    if action.lower() == 'watching':
        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=status))

【问题讨论】:

    标签: python python-3.x bots discord.py


    【解决方案1】:

    我认为您应该研究一下 ArgParse,这是一个解析参数的标准 Python 库。

    import argparse
    if __name__ == "__main__":     
        parser = argparse.ArgumentParser(description='Process some integers.')
        parser.add_argument('command')
        parser.add_argument('multi_word')
        parser.add_argument('something_else')
    
        args = parser.parse_args()
    
        print(args.command)
        print(args.multi_word)
        print(args.something_else)
    

    输出:

    > python test.py playing "Counterstrike: Global Offensive" another
    playing
    Counterstrike: Global Offensive
    another
    

    你调用你的函数而不是打印。

    编辑:对不起,我没有看到你试图使用 Discord 的东西。

    【讨论】:

    • 不用担心,我仍然非常感谢您的回复! :) 显然有人不喜欢你的回答
    【解决方案2】:

    这与 Python 无关,仅与 discord bot 库有关。

    相应地,检查the documentation for discord.py提供了三种方法:

    要使用中间有空格的单词,你应该引用它:

    或

    有时您希望用户传递不确定数量的参数。该库支持这一点,类似于在 Python 中如何完成变量列表参数:

    @bot.command()
    async def test(ctx, *args):
        await ctx.send('{} arguments: {}'.format(len(args), ', '.join(args)))
    

    这允许我们的用户随意接受一个或多个参数。这类似于位置参数,因此应该引用多字参数。

    或

    当您想自己处理参数的解析或不想将多词用户输入包装到引号中时,您可以要求库将其余部分作为单个参数提供给您。我们通过使用仅关键字参数来做到这一点,如下所示:

    @bot.command()
    async def test(ctx, *, arg):
       await ctx.send(arg)
    

    【讨论】:

    • 啊。我以为我被卡住了,因为当我输入多个参数时,我习惯性地使用单引号并且它不起作用。您的其他 2 个答案我需要尝试才能理解,但谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2012-10-22
    • 2023-01-12
    • 2020-05-15
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多