Python 无法在exec中等待
嗨,我正在尝试让我的discord机器人执行我键入的操作,我是我的discord客户端,我想使用exec()+这只是为了测试和实验,所以它是否不安全并不重要 我的部分代码:Python 无法在exec中等待,python,python-3.x,discord,discord.py,Python,Python 3.x,Discord,Discord.py,嗨,我正在尝试让我的discord机器人执行我键入的操作,我是我的discord客户端,我想使用exec()+这只是为了测试和实验,所以它是否不安全并不重要 我的部分代码: import discord client = discord.Client() @client.event async def on_message(message): if message.author == client.user: return if message.conten
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('2B: '):
exec(message.content[4:]) # <--- here is the exec()
.
.
.
错误:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Shiyon\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\Shiyon\Desktop\dm_1.py", line 12, in on_message
exec(message.content[4:])
File "<string>", line 1
await client.send_message(message.channel, 'please stay quiet -.-')
^
SyntaxError: invalid syntax
忽略on_消息中的异常
回溯(最近一次呼叫最后一次):
文件“C:\Users\Shiyon\AppData\Local\Programs\Python\36\lib\site packages\discord\client.py”,第307行,在运行事件中
getattr(自身,事件)的收益率(*args,**kwargs)
文件“C:\Users\Shiyon\Desktop\dm_1.py”,第12行,在on_消息中
exec(message.content[4:]
文件“”,第1行
等待客户。发送消息(message.channel,“请保持安静-。-”)
^
SyntaxError:无效语法
我认为这可能是您的问题:
请注意,即使在传递给exec()函数的代码上下文中,return和yield语句也不能在函数定义之外使用
从
这应该更好地发挥作用:
await eval(input)
如果您也希望能够使用非协同程序,您可以在等待eval返回之前进行检查
下面是一个片段,它似乎做了一些您想要的事情:
@commands.command(pass_context=True, hidden=True)
@checks.is_owner()
async def debug(self, ctx, *, code : str):
"""Evaluates code."""
code = code.strip('` ')
python = '```py\n{}\n```'
result = None
env = {
'bot': self.bot,
'ctx': ctx,
'message': ctx.message,
'server': ctx.message.server,
'channel': ctx.message.channel,
'author': ctx.message.author
}
env.update(globals())
try:
result = eval(code, env)
if inspect.isawaitable(result):
result = await result
except Exception as e:
await self.bot.say(python.format(type(e).__name__ + ': ' + str(e)))
return
await self.bot.say(python.format(result))
说明编辑:
await
关键字只在上下文中起作用,因为它在循环中暂停执行时发挥了一些神奇的作用
exec
函数始终返回None
,并丢失它执行的任何语句的返回值。相反,eval
函数返回其语句的返回值
client.send_message(…)
返回需要在上下文中等待的可等待对象。通过在返回eval
时使用wait
,我们可以很容易地做到这一点,通过先检查它是否可等待,我们还可以执行非协同路由。no。在这种情况下,错误将更改为:TypeError:object NoneType不能用于'wait'表达式中。
@Blimmo@shiyonsufa您可能应该使用eval
而不是exec
。由于python中的所有内容都会返回一些内容,因此它实际上没有太大的不同,但允许您处理wait.and eval result-->wait client.send_message(message.channel,“……是的,怎么了?”)^SyntaxError:invalid syntax
@shiyonsufa在使用命令时不要键入wait。如果您仍然感到困惑,请阅读我添加到答案中的解释。顺便说一句,代码片段的try块是您真正需要的全部,其余部分用于错误处理,诸如此类result=eval(message.content[4:])等待结果
@commands.command(pass_context=True, hidden=True)
@checks.is_owner()
async def debug(self, ctx, *, code : str):
"""Evaluates code."""
code = code.strip('` ')
python = '```py\n{}\n```'
result = None
env = {
'bot': self.bot,
'ctx': ctx,
'message': ctx.message,
'server': ctx.message.server,
'channel': ctx.message.channel,
'author': ctx.message.author
}
env.update(globals())
try:
result = eval(code, env)
if inspect.isawaitable(result):
result = await result
except Exception as e:
await self.bot.say(python.format(type(e).__name__ + ': ' + str(e)))
return
await self.bot.say(python.format(result))