Problems importing python module

I am trying to use the python bitstring module in a script and getting an import error. This error does not occur when working in interactive mode.

Here is the code:

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

At startup:

 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 

Everything is fine! This is the same interpreter that is controlled by the same user. Any pointers?

+6
source share
3 answers

I predict that you created bitstring.py in your current directory.

+7
source

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

As python moves sys.path from front to end, the modules in the current directory - even if they are accidentally created - outshine the ones in the system library directories.

+1
source

The Google App Engine actually had a similar problem at some point. The simplest solution is to simply comment out the violation line or use try ... except. Obviously, it will not work here.

In this case, the problem was in the initialization order. After half a second, a similar line of code was called successfully. Their decision? refactoring .: - (

The best I've seen is a dynamic class lookup: bitstring.__dict__.get("BitArray") or getattr(bitstring, "BitArray"); . It's not perfect (and I believe I even saw them return null), but I hope it can get you somewhere.

0
source

Source: https://habr.com/ru/post/889731/


All Articles