contents of io.py
class IO:
def __init__(self):
self.ParsingFile = '../list'
def Parser(self):
f = open(ParsingFile, 'r')
print(f.read())
contents of main.py
import sys
sys.path.insert(0, "lib/")
try:
import io
except Exception:
print("Could not import one or more libraries.")
exit(1)
print("Libraries imported")
_io_ = io.IO()
When I run python3 main.py I get the following error:
Libraries imported
Traceback (most recent call last):
File "main.py", line 11, in <module>
_io_ = io.IO()
AttributeError: module 'io' has no attribute 'IO'
Any idea what's going wrong?
My file was called io. It seems that there already exists a package called io which caused the confusion.
Your package name (io) conflicts with the Python library's package with the same name, so you actually import a system package.
You can check this by printing io.__all__.
Changing io.py to something else is probably the best way to go to avoid similar problems. Otherwise, you can use an absolute path.
try
from io import IO
That worked for me when trying to import classes from another file
this has more information:
Python module import - why are components only available when explicitly imported?
Related
My directory looks like this
When I start directly with PyCharm it works.
But when I try to start the script with a commandline I get this error messsage
> python .\PossibilitiesPlotter.py
Traceback (most recent call last):
File "C:\Users\username\PycharmProjects\SwapMatrixPlotter\possibilitiesplotter\PossibilitiesPlotter.py", line 7, in <module>
from plotterresources.PlotterProps import PlotterProps
ModuleNotFoundError: No module named 'plotterresources'
This is how the import looks from my main class PossibilitesPlotter.py
import sys
sys.path.append("plotterresources/PlotterProps.py")
from csv import reader
from pathlib import Path
from plotterresources.PlotterProps import PlotterProps
from possibilitiesplotter.PossibilitiesGraph import PossibilitiesGraph
from possibilitiesplotter.PossibilitiesModel import PossibilitiesModel
class PossibilitiesPlotter:
As a workaround, add the following line to PossibilitesPlotter.py:
sys.path.append("../plotterresources/PlotterProps.py")
This will add the directory one level above the commandline pwd to the PATH variable. So this is always relative to the location of the calling script/shell.
Thus in general:
NEVER append to the PATH/PYTHONPATH variable from within modules. Instead restructure your module. For more details, take a look at the documentation on Packaging Python Projects
I have a file structure that looks like this:
Liquid
|
[Truncate]
|_General_parsing
[Truncate]
.....|_'__init__.py'
.....|_'Processer.py'
.....|'TOKENIZER.py'
|_'__init__.py'
|_'errors.py'
[Truncate]
I want to import errors.py from Processer.py. Is that possible? I tried to use this:
from ..errors import *; error_manager = errorMaster()
Which causes this:
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 17, in <module>
from ..errors import *; error_manager = errorMaster()
ImportError: attempted relative import with no known parent package
[Finished in 0.125s]
I've seen this post, but it's no help, even if it tries to solve the same ImportError. This isn't, either (at least not until I edited it), since I tried:
import sys
sys.path.insert(1, '../Liquid')
from errors import *; error_manager = errorMaster()
That gives
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 19, in <module>
from errors import *; error_manager = errorMaster()
ModuleNotFoundError: No module named 'errors'
[Finished in 0.162s]
EDIT: Nevermind! I solved it! I just need to add .. to sys.path! Or . if .. doesn't solve your problem. But if those don't solve your problem: use some pathlib (came in python3.4+) magic and do:
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent))
or, if you want to use os: (gotten from this StackOverflow answer)
import os
os.path.join(os.path.dirname(__file__), '..')
I solved it! I have to add .. to sys.path instead
I am using Pickle in Python2.7. I am getting error while using cPickle.load() method. The code and error is shown below. Can someone guide me through this?
Code:
#! usr/bin/python
import cPickle
fo = open('result','rb')
dict1 = cPickle.load(fo)
Error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 7, in <module>
dicts = cPickle.load(fo)
ImportError: No module named options
It seems like you can not do
import options
but when you or someone else did
cpickle.dump(xxx, open('result', 'rb'))
there was an object with a class or function of a module options that existed at this point in time, in xxx.
Solution
You can open the file binarily and replace options with the module you replaced the old module options with.
You probably created the file in your package like in module package.main by executing the file main.py or something like it, having a module options in the same directory.
Now you do import package.main, try to read the file and options is now called package.options and the module options can not be found.
How did you create this file? How do you load it now? cPickle/pickle does not transfer source code - so if you use a function you need the module when you load it.
FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.
I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubuntu). How to make it fail, given that the import is not in my own code?
Even easier than messing with __import__ is just inserting None in the sys.modules dict:
>>> import sys
>>> sys.modules['pwd'] = None
>>> import pwd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pwd
In your testing framework, before you cause docutils to be imported, you can perform this setup task:
import __builtin__
self.savimport = __builtin__.__import__
def myimport(name, *a):
if name=='pwd': raise ImportError
return self.savimport(name, *a)
__builtin__.__import__ = myimport
and of course in teardown put things back to normal:
__builtin__.__import__ = self.savimport
Explanation: all import operations go through __builtin__.__import__, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding __builtin__.__import__, as you see above, affords truly simple code).