I have setup the following structure: Python 201: Creating Modules and Packages.
The mymathpackage is available at that link.
When you run the code below:
import sys
sys.path.append('G:\MyPython\Package')
import mymath
print (mymath.add(4,5))
print (mymath.division(4, 2))
print (mymath.multiply(10, 5))
print (mymath.fibonacci(8))
print (mymath.squareroot(48))
Python Version: 3.4
outer __init__.py contents:
from add import add
from divide import division
from multiply import multiply
from subtract import subtract
from adv.fib import fibonacci
from adv.sqrt import squareroot
My goal is to call division,add,subtract, etc, but if I try to call the module I get:
Traceback (most recent call last):
File "G:\MyPython\Package\myscript.py", line 1, in <module>
import mymath
File "G:\MyPython\Package\mymath\__init__.py", line 1, in <module>
from add import add
ImportError: No module named 'add'
Python 3.x has changed import resolution. You must now specify a full relative import if you want to perform a relative import.
from .add import add
Related
I have this
folder_tree
and i want to import class from runner.py in crawlers.py
from scraper.runner import Runner
runner = Runner([{'name': 'my_name', 'urls': ["https://www.exaple.com/"]}])
runner.crawl()
but i got error
Traceback (most recent call last):
File "./scraper/crawlers/actor_crawler.py", line 3, in <module>
from scraper.runner import Runner
ModuleNotFoundError: No module named 'scraper'
Also, i tried relative import:
from ..runner import Runner
And got that:
ValueError: attempted relative import beyond top-level package
I've found the following link to be incredibly helpful in understanding how Python does imports.
The surefire way to ensure your module can be imported though is adding it to os.syspath. Try adding the following to the beginning of your script:
import os
import sys
sys.path.append(/path/to/scraper/scraper/runner.py)
from scraper.runner import Runner
runner = Runner([{'name': 'my_name', 'urls': ["https://www.exaple.com/"]}])
runner.crawl()
I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.
I have this structure
02.SensorTag/
sensortag_example.py
bluepy/bluepy/sensortag.py
bluepy/bluepy/btle.py
So the sensortag_example.py is importing the sensortag.py
import bluepy
from bluepy.bluepy import sensortag
When I ran the code it complains about the import from the sensortag.
Traceback (most recent call last):
File "sensortag_example.py", line 2, in <module>
from bluepy.bluepy import sensortag
File "/home/pi/Development/02.SensorTag/bluepy/bluepy/__init__.py", line 3, in <module>
from . import sensortag
File "/home/pi/Development/02.SensorTag/bluepy/bluepy/sensortag.py", line 1, in <module>
from bluepy.btle import UUID, Peripheral, DefaultDelegate, AssignedNumbers
ImportError: No module named 'bluepy.btle'
I've tried to add a new path but it didin't work. If I move the program to the first folder bluepy and change the import to "from bluepy import sensortag" it works, but I'll need to import other libs so I don't want to let it in bluepy folder.
I am trying to run this code:
https://gist.github.com/atotto/ae603b962115eef703c0011d8e652ea3
Thanks and best regards,
Edu
Because sensortag.py is in the same directory as btle.py, add a . in front of the import
from .btle import UUID, Peripheral, DefaultDelegate, AssignedNumbers
This is known as a relative import: https://docs.python.org/2.5/whatsnew/pep-328.html
As both btle.py and sensortag.py are in the same directory so by looking at your error I am assuming that you tried to import it from previous directory. So place from .btle import UUID in sensortag.py should solve the issue.
You should create two init.py file.
02.SensorTag/
sensortag_example.py
bluepy/__init__.py
bluepy/bluepy/__init__.py
bluepy/bluepy/sensortag.py
bluepy/bluepy/btle.py
According to the documentation, six supports adding custom renames to six.moves:
six.add_move(item)
Add item to the six.moves mapping. item should be a MovedAttribute or
MovedModule instance.
And:
class six.MovedModule(name, old_mod, new_mod)
Create a mapping for six.moves called name that references different
modules in Python 2 and 3. old_mod is the name of the Python 2 module.
new_mod is the name of the Python 3 module.
However, this code yields an ImportError for me:
from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves.mock import MagicMock
When I run it on Python 3.4.2 using six 1.9.0 I get this error:
Traceback (most recent call last):
File "test_six_moves.py", line 2, in <module>
from six.moves.mock import MagicMock
ImportError: No module named 'six.moves.mock'
The builtin moves are working just fine. How do I get this to work?
You can't import the name from within the move. Use:
from __future__ import print_function
from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock
print(mock.MagicMock)
This will give you:
# Python 2
<class 'mock.MagicMock'>
# Python 3
<class 'unittest.mock.MagicMock'>
Note that importing from within a move works for the ones that ship with six. For example: from six.moves.configparser import ConfigParser works.
This piece of code (from six.py) is why:
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name)
In fact, if you ran the following (meddling with private attributes is of course not recommended), your import would work:
import six
mod = six.MovedModule('mock', 'mock', 'unittest.mock')
six.add_move(mod)
six._importer._add_module(mod, "moves." + mod.name)
I have some troubles with importation of self-made modules, I just can't see what I am doing wrong.
I have a package named basics, which has all my base classes
I have a second package named components, and every module in componentsuses the modules from basics.
I have a script file, located in another folder, which calls upon the basics and components modules.
I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "H:/scripts/CIF_utilities/scripts/hello world.py", line 11, in <module>
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
File "H:\scripts\CIF_utilities\components\textwriter.py", line 23, in __init__
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
NameError: global name 'Layout' is not defined
There is my script: hello world.py
#hello world.py
import basics
from components.textwriter import *
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
cell=TW.writeText('Hello World',30e3)
cell.draw()
layout=Layout()
layout.addCell(cell)
layout.workCell=cell
layout.exportCIF('hello world',os.getcwd())
textwriter.py is the one giving the error. In init, I load some data from a preformatted file using the Layout class (which will make the import)
in textwriter.py
#texwriter.py
import basics
import os, os.path, sys
import re
from numpy import *
from scipy import *
class TextWriter:
def __init__(self,pathToCIF=None):
if pathToCIF==None:
path=os.path.split(textwriter.__file__)[0]
else:
path=pathToCIF
###line that crashes is here
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
self.alphabet=layout.workCell
There is the layout.py class:
#layout.py
import basics
from numpy import *
from scipy import *
import Tkinter
import tkFileDialog
import os, os.path
import re
import datetime
class Layout:
countCell=0
#classmethod
def getNewNumber(self):
Layout.countCell+=1
return Layout.countCell
def __init__(self,File=None):
self.cellList=[]
self.layerList=[]
self.nameFile=""
self.comments=""
self.workCell=None
if File!=None:
self.importCIF(File)
the init.py of the basics package contains all the necessary importations:
#__init__.py in basics folder
from baseElt import *
from cell import *
from layout import *
from transformation import *
the init.py from components is empty
I am currently using the anaconda 64bits distribution (python 2.7 if I recall well)
Thanks for your much needed help!
Since Layout is imported in basics/__init__.py, it only exists in the basics namespace, not in helloworld.py. Either access it with
layout = basics.Layout()
or explicitly import Layout into helloworld.py with
from basics import Layout
In textwriter.py, you want to switch
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
for
layout=basics.Layout(File=os.path.join(path,'alphabet.CIF'))
You may have similar problems along your code. it is good to note that it is not pythonic to use
from package import *
It is recommended to instead use
from package_or_module import specific_item
import package_or_module
Remember, if you import with regular import you have to use the module/package name to access the object you want (i.e. basics.Layout).