【问题标题】:how can I define this and call to use it?我该如何定义它并调用它?
【发布时间】:2020-04-13 13:45:17
【问题描述】:

我正在尝试定义此发送消息功能。但是有什么问题..

import asyncio
import websockets


async def send_msg(msg):
    async with websockets.client.Connect(url) as websocket:
        print("Connected to WebSocket!")

        await websocket.send(msg)
send_msg('hi')

loop = asyncio.get_event_loop()
task = loop.create_task(send_msg())
loop.run_until_complete(task)

TypeError: send_msg() missing 1 required positional argument: 'msg'

有人可以帮我吗?谢谢

【问题讨论】:

  • task = loop.create_task(send_msg()) 怎么样?它不应该包含msg 参数吗?
  • task = loop.create_task(send_msg(msg)) NameError: name 'msg' is not defined 这是我更改后得到的
  • 你需要传递一个字符串,例如task = loop.create_task(send_msg("hey!"))
  • 天哪,你是对的!但是在将它导入另一个之后我该如何使用它呢?我需要继续使用最后两行吗?
  • “在另一个中导入此内容后”到底是什么意思?

标签: python python-asyncio


【解决方案1】:

如果你想要一个以后可以使用的简单函数,你可以这样定义:

async def send(msg):
    async with websockets.client.Connect(url) as websocket:
        print("Connected to Spoon WebSocket!")

        await websocket.send(msg)


def send_msg(msg):
    loop = asyncio.get_event_loop()
    task = loop.create_task(send(msg))
    loop.run_until_complete(task)

那么你只需要导入你的.py文件并运行test01.send_msg('hello')

【讨论】:

  • 非常感谢先生!你是最棒的!!
  • 很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 2012-07-19
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多