【问题标题】:How to write this as a module?如何将其编写为模块?
【发布时间】:2016-04-25 10:46:37
【问题描述】:

我想问一下,如何在Python中将以下内容编写为模块。

    if message.content.startswith('!guess'):
        # Game Status updating
        now_playing = discord.Game(name='Guessing Game')
        await self.change_status(game=now_playing, idle=False)

        await self.send_message(message.channel, 'Guess a number between 1 to 10')

        def guess_check(m1):
            return m1.content.isdigit()

        guess = await self.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
        answer = random.randint(1, 10)
        if guess is None:
            fmt = 'Sorry, you took too long. It was {}.'
            await self.send_message(message.channel, fmt.format(answer))
            return
        if int(guess.content) == answer:
            await self.send_message(message.channel, 'You are right!')
        else:
            await self.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))

        # Game Status updating
        now_playing = discord.Game(name='')
        await self.change_status(game=now_playing, idle=False)

这样我就可以使用guessgame.guess() 来调用它

【问题讨论】:

标签: python python-3.x


【解决方案1】:

创建一个名为 guessgame.py 的 Python 模块文件,然后在其中定义:

"""
This is the module guessgame, it lives in the file guessgame.py
Put some documentation about your module here
"""
def guess(message):
   # Put your code here

然后从另一个模块,例如sample.py(或 Python/IPython shell 会话)你可以这样做:

import guessgame
guessgame.guess(message='something')       # What you wanted

RuntimeWarning: coroutine 'guess' 从未等待guessgame.guess()

# 'await' can only be used inside a coroutine
# if you want guess to be a coroutine, define it like below
async def guess(message):
   # Put your code that uses await
   # Now you can use await expressions

注意:

  • 您使用的是await,这需要格外小心,请在此处阅读更多信息:https://www.python.org/dev/peps/pep-0492/#examples-of-await-expressions
  • 不要在guessname.guess() 代码中重新定义guess 名称,因为您的函数已经被称为guess,如果您重新定义guess = ...,您将影响
  • 确保您的guessgame.guess() 传递了所有必需的参数,只是为了便于说明,我只包含了一个参数message
  • 我看到您在该代码中使用了self,这表明这应该是一个类的方法,而不是一个独立的函数?只是需要牢记!

【讨论】:

  • 我收到这个错误:- C:/Users/dell/Desktop/Python Projects/lapzbot/bot/lapzbot.py:208: RuntimeWarning: coroutine 'guess' was never awaited guessgame.guess()
  • 感谢您抽出宝贵时间帮助我。我在这里添加了完整的代码 pastebin.com/NbxasMDD 。希望你能看一次。 Ty 又这么多@bakkal
  • 没问题很高兴我能帮上忙!这就是我要做的。我将创建该代码/类等的空白 Python 模块和另一个使用它的模块。然后我会慢慢地将代码复制/粘贴到模块中,一一处理问题。重复直到整个程序就位并运行。
猜你喜欢
  • 1970-01-01
  • 2021-07-25
  • 2010-12-16
  • 1970-01-01
  • 2017-02-10
  • 2012-03-07
  • 2013-08-03
  • 2021-12-16
相关资源
最近更新 更多