AttributeError: module 'nats' has no attribute 'connect' - python

https://nats-io.github.io/nats.py/modules.html
Traceback (most recent call last):
File "c:\Users\lb\nats.py", line 22, in <module>
asyncio.run(main())
File "D:\anaconda\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "D:\anaconda\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:\Users\lb\nats.py", line 6, in main
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
AttributeError: module 'nats' has no attribute 'connect'
An Attribute error: I am not able to figure out what is the issue with 'connect'.
import asyncio
import nats
async def main():
# Connect to NATS!
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
# Receive messages on 'foo'
sub = await nc.subscribe("foo")
# Publish a message to 'foo'
await nc.publish("foo", b'Hello from Python!')
# Process a message
msg = await sub.next_msg()
print("Received:", msg)
# Close NATS connection
await nc.close()
if __name__ == '__main__':
asyncio.run(main())
Help me with this connect issue, please.

The solution is to rename your file to anything else.
When you type import nats python recursively tries to find a file or folder named nats. In this case the first file if will find is nats.py.
You never define a function named connect in your nats.py so that fails. You want to instead let the recursive import continue upto site_packages where the actual nats folder is that contains the connect function.
For example, if you name this file hello.py:
import hello
print(hello.hello)
print(hello)
print(hello.hello.hello)
You will see that all 3 print statements print the same thing, since hello will be the file itself.
Simply renaming your file anything else will prevent python from finding the module too soon and will keep searching till it find the correct module.

I just ran your code and got no error.
Try uninstalling and reinstalling nats:
pip install nats-py

Related

Error "list index out of range" in Python 3

I am currently programming a Discord Bot for a friend.
I have a new PC and now the following error occured after using my "!meme" command.
It worked on my old Laptop, but i dont have it anymore...
Code for the command:
elif '!meme' in message.content:
random_message_i = ["Here you go:", "Classic one:", "This one is good:", "lol xD:"]
await message.channel.send(f"{random.choice(random_message_i)}")
meme_file_paths = [os.path.abspath(_) for _ in glob.glob("botmemes/*.png")]
random_meme_i = random.choice(meme_file_paths)
await message.channel.send(file=discord.File(random_meme_i))
print("[INFO] Last command: !meme")
Error:
Traceback (most recent call last):
File "C:\Users\cxyro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\cxyro\Desktop\DiscordBot\discordbot.py", line 103, in on_message
random_meme_i = random.choice(meme_file_paths)
File "C:\Users\cxyro\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
(Yes, the code ant the memes are in the same main folder...)
Can somebody help me?
As far as, I can see , it occurs when you pass an empty list to choice() function. (in case, file not found) P.S :- Make sure, you are executing that script within the same directory where your code and meme is kept. otherwise, your current working directory gets changed and your code won't be able to find the meme path. you can verify this by writing this code in a print statement in your script:
import os; os.getcwd()

Python script runs correctly in terminal gives error when run via crontab

I have written a short python script that uses bleak and asyncio to control a bluetooth LE device. The script works exactly as intended when I run it manually in pycharm or terminal, however I want to run it at specific intervals using crontab.
I've searched for a solution and tried adding absolute paths as well as logging errors. I have found that the script throws an error when run from crontab but I don't quite understand how to fix it.
Here is the script:
#!/usr/bin/python
from bleak import BleakClient
import asyncio
address = "DFB18A2C-6BAB-439E-AF05-485FB4259B75"
MODEL_NBR_UUID = "99FA0002-338A-1024-8A49-009C0215F78A"
async def main(address):
async with BleakClient(address) as client:
for i in range(3):
await client.write_gatt_char(MODEL_NBR_UUID, bytes.fromhex("0800"))
time.sleep(0.5)
asyncio.run(main(address))
And here is the error from crontab log:
Traceback (most recent call last):
File "/Users/emileberhard/PycharmProjects/BedMove/main.py", line 19, in <module>
asyncio.run(main(address))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/emileberhard/PycharmProjects/BedMove/main.py", line 13, in main
async with BleakClient(address) as client:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/client.py", line 61, in __aenter__
await self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/client.py", line 78, in connect
device = await BleakScannerCoreBluetooth.find_device_by_address(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/scanner.py", line 220, in find_device_by_address
return await cls.find_device_by_filter(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/scanner.py", line 249, in find_device_by_filter
async with cls(detection_callback=apply_filter, **kwargs):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/scanner.py", line 44, in __init__
self._manager = CentralManagerDelegate.alloc().init()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/CentralManagerDelegate.py", line 88, in init
raise BleakError("Bluetooth device is turned off")
bleak.exc.BleakError: Bluetooth device is turned off
Exception ignored in: <CentralManagerDelegate objective-c instance 0x0>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/bleak/backends/corebluetooth/CentralManagerDelegate.py", line 102, in __del__
IndexError: NSRangeException - Cannot remove an observer <CentralManagerDelegate 0x7fd036fbe0b0> for the key path "isScanning" from <CBCentralManager 0x600000aab100> because it is not registered as an observer.
Exception ignored in: <function CentralManagerDelegate.__del__ at 0x7fd01863cca0>
I'm running MacOS btw!
Thanks in advance!
remove that command from your cronjob.
do this, select your editor of choice from the list.
sudo crontab -e
then add your cronjob, exit and then save (these will run as root)
0 0 * * * /usr/local/bin/python3.9 /users/emileberhard/PycharmProjects/BedMove/main.py >> /users/emileberhard/out2.txt 2>&1
This happens when you have bluetooth off on your OSX device.

Cannot install modules using micropip (Pyodide 0.19.0)

I am facing an error of "ImportError: cannot import name 'fetch' from 'js' (unknown location)" whenever I try to install any module in pyodide.
Initially, I tried the following lines of code :
await pyodide.loadPackage('micropip')
await pyodide.runPythonAsync(`
import micropip
await micropip.install('textblob')
from textblob import TextBlob
// ... something
`)
but it still gave the above error.
then i tried to run the code from the official documentation (https://pyodide.org/en/stable/usage/loading-packages.html)
await pyodide.loadPackage("micropip");
await pyodide.runPythonAsync(`
import micropip
micropip.install('snowballstemmer')
import snowballstemmer
stemmer = snowballstemmer.stemmer('english')
print(stemmer.stemWords('go goes going gone'.split()))
`);
but it still gave me the same error.
could someone guide me how to solve this?
i also tried to loadpackage('js') and importing it inside the runPythonAsync but it still failed.
here's the full version of the error :-
PythonError: Traceback (most recent call last):
File "/lib/python3.9/asyncio/futures.py", line 201, in result
raise self._exception
File "/lib/python3.9/asyncio/tasks.py", line 258, in __step
result = coro.throw(exc)
File "/lib/python3.9/site-packages/micropip/_micropip.py", line 185, in install
transaction = await self.gather_requirements(requirements, ctx, keep_going)
File "/lib/python3.9/site-packages/micropip/_micropip.py", line 175, in gather_requirements
await gather(*requirement_promises)
File "/lib/python3.9/asyncio/futures.py", line 284, in __await__
yield self # This tells Task to wait for completion.
File "/lib/python3.9/asyncio/tasks.py", line 328, in __wakeup
future.result()
File "/lib/python3.9/asyncio/futures.py", line 201, in result
raise self._exception
File "/lib/python3.9/asyncio/tasks.py", line 256, in __step
result = coro.send(None)
File "/lib/python3.9/site-packages/micropip/_micropip.py", line 284, in add_requirement
metadata = await _get_pypi_json(req.name)
File "/lib/python3.9/site-packages/micropip/_micropip.py", line 88, in _get_pypi_json
return json.loads(await fetch_string(url))
File "/lib/python3.9/site-packages/micropip/_micropip.py", line 60, in fetch_string
return await (await pyfetch(url, **kwargs)).string()
File "/lib/python3.9/site-packages/pyodide/http.py", line 229, in pyfetch
from js import fetch as _jsfetch, Object
ImportError: cannot import name 'fetch' from 'js' (unknown location)
guidance needed.
If you are trying to achieve this in node.js you need to install node-fetch (or any other library that provides fetch function) and make it available as global/globalThis element so that pyodide's js can also access it.
For your example from the documentation regarding snowballstemmer, I was able to run it with the following code inside a file named example.mjs and executing it as node example.mjs:
import fetch from "node-fetch";
globalThis.fetch = fetch;
let pyodide_pkg = await import("./pyodide/pyodide.js");
let pyodide = await pyodide_pkg.loadPyodide({
indexURL: "pyodide",
});
await pyodide.loadPackage("micropip");
await pyodide.runPythonAsync(`
import micropip
await micropip.install('snowballstemmer')
import snowballstemmer
stemmer = snowballstemmer.stemmer('english')
print(stemmer.stemWords('go goes going gone'.split()))
`);
This gives the expected output and the stemmed results as:
['go', 'goe', 'go', 'gone']
PS: While it is a bad practice to use global/globalThis in general but since fetch in browsers is available as a member of window (i.e. window.fetch), I guess it is okay to use it this way.

Exception has occurred: NoEntryPointError

I am using Discord.py, and while making a command handler using COG, I got this error.
This is the main.py (main bot file)
# Command Handler: Import cog files.
for file in os.listdir("./cogs"): # lists all the cog files inside the cog folder.
if file.endswith(".py"): # It gets all the cogs that ends with a ".py".
name = file[:-3] # It gets the name of the file removing the ".py"
client.load_extension(f"cogs.{name}") # This loads the cog.
Here is the link to the only file I have in my ./cog/ directory, named "Hellgoodbye.py".
https://pastebin.com/TdE8FPxq
The error I get when I do "python .\main.py" in my VSCode terminal, I get the following error:
Traceback (most recent call last):
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 612, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs.Hellogoodbye' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\main.py", line 141, in <module>
client.load_extension(f"cogs.{name}") # This loads the cog.
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 615, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.Hellogoodbye' has no 'setup' function
Can someone help me fix the error. i really do not know what is going on.
As the error says you don't have setup function. It is necesary for an extension to load.
import discord
from discord.ext import commands
class Name(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Name(bot))
This is an example of a cog file. As you can see at the very end of the code there is the setup function. It should be a standalone function which is not defined inside of the class.
Answer:
I moved
def setup(bot)
bot.add_cog(Hellogoodbye(bot))
To the end of the file, and it is working now, besides the fact I have some other issues, but the error I asked about is fixed by this.

ladon throwing an AttributeError

I'm trying to get ladon working, however, I don't seem to be able to define the service properly.
Specifically, even with a minimal test case, it's throwing
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 332, in __call__
self.import_services(self.service_list)
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 288, in import_services
__import__(service)
File "D:\Workspaces\Python\SOAPManager.py", line 20, in <module>
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
File "C:\Python33\lib\site-packages\ladon\ladonizer\decorator.py", line 118, in decorator
injector.__doc__ = ladon_method_info._doc
AttributeError: 'NoneType' object has no attribute '_doc'
My Run.py contains:
from ladon.server.wsgi import LadonWSGIApplication
from os.path import abspath, dirname
from wsgiref.simple_server import make_server
application = LadonWSGIApplication(
['SOAPManager'],
[dirname(abspath(__file__))],
catalog_name='API',
catalog_desc='API Description')
httpd = make_server('0.0.0.0', 8004, application)
print("Listening on port 8004...")
# Respond to requests until process is killed
httpd.serve_forever()
And the minimal test case in SOAPManager.py:
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType
from ladon.compat import PORTABLE_STRING
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
def Authenticate(Username, Password):
return "Test"
The error is being raised from within the ladonize decorator. It seems to be occuring when trying to build up the definition of the service. Specifically, in ladon the decorator calls collection.add_service_method which returns None instead of a method. I think it's failing a line-number check.
firstlineno = f.__code__.co_firstlineno
# get an ast-analyzed object of the source file
sinfo = self.source_info(src_fname)
...
for clsname,v in sinfo.items():
if firstlineno>v[0] and firstlineno<=v[1]:
For some reason that check is failing so the method defaults to returning None.

Categories

Resources