Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems importing python module

I'm trying to use python's bitstring module in a script and am getting an import error. This error does not happen when running from interactive mode.

Here's the code:

import bitstring
b = bitstring.BitArray(bin='001001111')

When run like this:

python test.py

I get this:

AttributeError: 'module' object has no attribute 'BitArray'

However, when I do this:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bitstring
>>> b = bitstring.BitArray(bin='001001111')
>>> print b
0b001001111

It works just fine! It's the same interpreter being run by the same user. Any pointers?

like image 886
nnachefski Avatar asked Jun 03 '11 19:06

nnachefski


2 Answers

I predict you have created a bitstring.py in your current directory.

like image 129
Michael Kent Avatar answered Oct 21 '22 00:10

Michael Kent


The problem is caused by a bitstring.py file in sys.path of test.py, but not in that of the interactive python shell. Most likely, there's a bitstring.py file in the directory test.py is in, and you started your shell from another working directory.

Since python traverses sys.path from front to end, modules in the current directory - even if accidentally created - overshadow those in system library directories.

like image 34
phihag Avatar answered Oct 21 '22 02:10

phihag