ImportError: cannot import name 'entrenamiento' - python-3.x

I'm taking Python again after a long time.
I'm developing a little software to help me learn a new lengauge (japanese)
I tried to make a class and import it, but it did't work. Just for testing, I created a very simple class and when I tried to import it I got an error.
Here is the code (both files trainer.py and prueba.py are in the same folder):
file trainer.py
class trainer:
def entrenamiento(t,dicc):
print(t)
print(dicc)
file prueba.py
from trainer import entrenamiento
entrenamiento(1,2)
When I run prueba.py I get the following:
C:\Users\nico\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/nico/PycharmProjects/japanese/prueba.py
Traceback (most recent call last):
File "C:/Users/nico/PycharmProjects/japanese/prueba.py", line 1, in <module>
from trainer import entrenamiento
ImportError: cannot import name 'entrenamiento'
Process finished with exit code 1
I also tried with a different code in prueba.py:
import trainer
trainer.entrenamiento(1,2)
and I got this:
C:\Users\nico\AppData\Local\Programs\Python\Python36-32\python.exe
C:/Users/nico/PycharmProjects/japanese/prueba.py
Traceback (most recent call last):
File "C:/Users/nico/PycharmProjects/japanese/prueba.py", line 3, in <module>
trainer.entrenamiento(1,2)
AttributeError: module 'trainer' has no attribute 'entrenamiento'
Process finished with exit code 1
Finally, just for checking I tried the following
file trainer.py
class trainer:
print('hello world')
file prueba.py
import trainer
and I got no error
C:\Users\nico\AppData\Local\Programs\Python\Python36-32\python.exe
C:/Users/nico/PycharmProjects/japanese/prueba.py
hello world
Process finished with exit code 0
I'm working with Python 3.6.5 and PyCharm 2018.1.4 Community Edition
Is there any mistake in my coding or maybe a configuration issue?
I thank you in advance for your help

Uhm so, you made a little mistake with your import in prueba.py
it should be:
from trainer import trainer
trainer.entrenamiento(1,2)
where the first trainer points to trainer.pyand the second points to the class.
you can now access the function defined inside the class using the syntax class.function eg. trainer.entrenamiento(1,2)
i would recommend to change either the name of trainer.py or the class trainer as it's obviously confusing.

Related

Yolov5 why is application complaining?

I trying to use a python app from github but when trying to launch the app I get the following error which I cannot understand why.
Exception has occurred: ModuleNotFoundError
No module named 'utils'
File "C:\Users\ah\Documents\myProjects\footballanalysis-main\Bird's eye view\yolov5\models\experimental.py", line 11, in
from utils.downloads import attempt_download
File "C:\Users\ah\Documents\myProjects\footballanalysis-main\Bird's eye view\elements\yolo.py", line 4, in
from yolov5.models.experimental import attempt_load
File "C:\Users\ah\Documents\myProjects\footballanalysis-main\Bird's eye view\main.py", line 1, in
from elements.yolo import YOLO

How to catch an exception and get exception type in Python?

[Question] I need user to provide GDrive link to their kaggle.json file so I can set it up, when the script is run first time without kaggle.json file it throws an error and I am trying to handle it but without any success, my first question is same as title of this post, and second is does this make any sense all of this? Is there a better way to do this?
[Background] I am trying to write a script that acts as an interface providing limited access to functionalities of Kaggle library so that it runs in my projects and still being able to share it on GitHub so that others can use it in similar projects, I will bundle this along with configuration management tool or with shell script.
This is the code:
#!/usr/bin/env python3
import os
import sys
import traceback
import gdown
import kaggle
import argparse
"""
A wrapper around the kaggle library that provides limited access to the kaggle library
"""
#*hyperparameters
dataset = 'roopahegde/cryptocurrency-timeseries-2020'
raw_data_folder = './raw'
kaggle_api_file_link = None
#*argument parser
parser = argparse.ArgumentParser(description="download dataset")
parser.add_argument('--kaggle_api_file', type=str, default=kaggle_api_file_link, help="download and set kaggle API file [Gdrive link]")
parser.add_argument("--kaggle_dataset", type=str,
default=dataset, help="download kaggle dataset using user/datasets_name")
parser.add_argument("--create_folder", type=str, default=raw_data_folder, help="create folder to store raw datasets")
group = parser.add_mutually_exclusive_group()
group.add_argument('-preprocess_folder', action="store_true", help="create folder to store preprocessed datasets")
group.add_argument('-v', '--verbose', action="store_true", help="print verbose output")
group.add_argument('-q', '--quiet', action="store_true", help="print quiet output")
args = parser.parse_args()
#*setting kaggle_api_file
if args.kaggle_api_file:
gdown.download(args.kaggle_api_file, os.path.expanduser('~'), fuzzy=True)
#*creating directories if not exists
if not os.path.exists(args.create_folder):
os.mkdir(args.create_folder)
if not os.path.exists('./preprocessed') and args.preprocess_folder:
os.mkdir('./preprocessed')
def main():
try:
#*downloading datasets using kaggle.api
kaggle.api.authenticate()
kaggle.api.dataset_download_files(
args.kaggle_dataset, path=args.create_folder, unzip=True)
kaggle.api.competition_download_files
#*output
if args.verbose:
print(
f"Dataset downlaoded from https://www.kaggle.com/{args.kaggle_dataset} in {args.create_folder}")
elif args.quiet:
pass
else:
print(f"Download Complete")
except Exception as ex:
print(f"Error occured {type(ex)} {ex.args} use flag --kaggle_api_file to download and set kaggle api file")
if __name__ == '__main__':
sys.exit(main())
I tried to catch IOError and OSError instead of catching generic Exception, still no success. I want to print a message telling user to use --kaggle_api_file flag to set up kaggle.json file.
This is the error:
python get_data.py
Traceback (most recent call last):
File "get_data.py", line 7, in <module>
import kaggle
File "/home/user/.local/lib/python3.8/site-packages/kaggle/__init__.py", line 23, in <module>
api.authenticate()
File "/home/user/.local/lib/python3.8/site-packages/kaggle/api/kaggle_api_extended.py", line 164, in authenticate
raise IOError('Could not find {}. Make sure it\'s located in'
OSError: Could not find kaggle.json. Make sure it's located in /home/user/.kaggle. Or use the environment method.

ImportError importing class from file in same directory Python

I have two files
import_1.py
class Test:
pass
import_2.py
from import_1 import Test
Directory structure is:
Python_Testing
import_1
import_2
When I run import_2.py I get the error
File "c:\Users\61403\Desktop\Python_Testing\import_2.py", line 1, in <module>
from import_1 import Test
ImportError: cannot import name 'Test' from 'import_1' (c:\Users\61403\Desktop\Python_Testing\import_1.py)
Hovering over the Test on VSCode, it knows that it is a class.
Why is this error popping up?
Extremely silly. Auto Save wasn't turned on on my new laptop, so apparently import_1.py wasn't getting saved or sth and so could never be imported.

asyncio import issues - no attribute 'StreamReader'

I have had asyncio and websockets work fine several times, but for some reason it sometimes refuses to run and will refuse to ever run again. I have had this happen across multiple devices, with code as simple as just imports:
import asyncio
import json
import websockets
Interestingly, when using Pydroid3 on Android, any code I write with asyncio works fine, but only until I save it to a file. Once it's been saved, it stops working. I can copy all the text and paste it to a new, unsaved file and it again works fine until saved. This awful solution does not work for Windows, unfortunately. I am using Python 3.9.0 for Windows. The stacktrace produced by running the code shown above is as follows:
Traceback (most recent call last):
File "C:\Users\user\Documents\AtomTests\socket.py", line 1, in <module>
import asyncio
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\__init__.py", line 8, in <module>
from .base_events import *
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 23, in <module>
import socket
File "C:\Users\user\Documents\AtomTests\socket.py", line 3, in <module>
import websockets
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\__init__.py", line 3, in <module>
from .auth import * # noqa
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\auth.py", line 12, in <module>
from .exceptions import InvalidHeader
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\exceptions.py", line 33, in <module>
from .http import Headers, HeadersLike
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\http.py", line 70, in <module>
async def read_request(stream: asyncio.StreamReader) -> Tuple[str, "Headers"]:
AttributeError: partially initialized module 'asyncio' has no attribute 'StreamReader' (most likely due to a circular import)
[Finished in 0.158s]
I've searched a bit for this error, but either it's uncommon or I'm just blind, because I couldn't find anything. Has anyone else had this happen to them?
Your local socket.py file is shadowing Python’s socket module. Rename your file and your imports will work.

Running neo4j-Python code in Eclipse with Pydev under ArchLinux

so I installed neo4j on ArchLinux (AUR Link) and want to test it using python 3.2.
I am using python 3.2, Eclipse with Pydev.
I tried following code from the neo4j website, allthough I think it was still 2.7 python code and I tried to convert it to Python 3.2 code.
Here's the code:
import os
libpath = '/usr/share/java/neo4j'
os.environ['CLASSPATH'] = ';'.join( [ os.path.abspath(p) for p in
os.listdir(libpath)])
from neo4j import GraphDatabase
# Create a database
db = GraphDatabase('/home/USERNAME/.db/neo4j/HelloWorld')
# All write operations happen in a transaction
with db.transaction:
firstNode = db.node(name='Hello')
secondNode = db.node(name='world!')
# Create a relationship with type 'knows'
relationship = firstNode.knows(secondNode, name='graphy')
# Read operations can happen anywhere
message = ' '.join([firstNode['name'], relationship['name'], secondNode['name']])
print(message)
# Delete the data
with db.transaction:
firstNode.knows.single.delete()
firstNode.delete()
secondNode.delete()
# Always shut down your database when your application exits
db.shutdown()
But I get following error message:
Traceback (most recent call last):
File "/home/USERNAME/PATH/TO/src/neo4j-HelloWorld.py", line 12, in <module>
from neo4j import GraphDatabase
File "/usr/lib/python3.2/site-packages/neo4j_embedded-1.6-py3.2.egg/neo4j/__init__.py", line 29, in <module>
from neo4j.core import GraphDatabase, Direction, NotFoundException, BOTH, ANY, INCOMING, OUTGOING
File "/usr/lib/python3.2/site-packages/neo4j_embedded-1.6-py3.2.egg/neo4j/core.py", line 19, in <module>
from _backend import *
ImportError: No module named _backend
I just can't figure out what's wrong!
I tried to set the CLASSPATH as described here, but it doesn't change anything.
I would really appreciate any help!
Did you run the code through 2to3?
If not, I suggest you do.
I think the problem is that the relative import syntax changed in 3.x, see PEP328 for details.
e.g. the offending import in core.py should probably say from ._backend import *

Resources