Rectangle 27 3

What's the name of your script? There could be a name collision going on if the name of your script is "shodan", i.e. the same name as the Shodan library. There was also an issue with Python 3 that caused some import problems, but if you're using the latest version of the Shodan API library that should be resolved. And I echo the comment of luc that the indentation looks wrong, so you will need to fix that as well in order for the script to execute.

python - ImportError: cannot import name WebAPI - Stack Overflow

python importerror python-import
Rectangle 27 3

What's the name of your script? There could be a name collision going on if the name of your script is "shodan", i.e. the same name as the Shodan library. There was also an issue with Python 3 that caused some import problems, but if you're using the latest version of the Shodan API library that should be resolved. And I echo the comment of luc that the indentation looks wrong, so you will need to fix that as well in order for the script to execute.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - ImportError: cannot import name WebAPI - Stack Overflow

python importerror python-import
Rectangle 27 44

This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready -- by using from x import y. This is essentially the same as

import x
y = x.y
del x

Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

a = module() # import a

# rest of module

a.update_contents(real_a)
import x
import x
class cls:
    def __init__(self):
        self.y = x.y

Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.

python - ImportError: Cannot import name X - Stack Overflow

python importerror python-import
Rectangle 27 44

This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready -- by using from x import y. This is essentially the same as

import x
y = x.y
del x

Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

a = module() # import a

# rest of module

a.update_contents(real_a)
import x
import x
class cls:
    def __init__(self):
        self.y = x.y

Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.

python - ImportError: Cannot import name X - Stack Overflow

python importerror python-import
Rectangle 27 3

What version of scikit-learn are you using? It looks like the latest, when I install for Python 3.5, is 0.17.1. Checking in the console:

import sklearn
sklearn.__version__
'0.17.1'

According to the documentation for this version that "model_selection" package doesn't exist. It does exist in the dev version. This should be why it is complaining.

Thanks, but there might be something wrong with the dev version. When i try to run a script which run successfully in 0.17.1, it shows like this: from .pairwise_fast import _chi2_kernel_fast, _sparse_manhattan ImportError: dlopen(/Users/QinqingLiu/anaconda3/lib/python3.5/site-packages/sklearn/metrics/pairwise_fast.cpython-35m-darwin.so, 2): Library not loaded: libmkl_intel_lp64.dylib Referenced from: /Users/QinqingLiu/anaconda3/lib/python3.5/site-packages/sklearn/metrics/pairwise_fast.cpython-35m-darwin.so Reason: image not found

osx - Python 3 ImportError: cannot import name 'model selection' OS X ...

python osx python-3.x scikit-learn anaconda
Rectangle 27 91

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run

import os
os.getcwd()

However, let's say you're using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.

PSA: if you've come to this SO question because you're getting this error in jupyter-notebook, then see below, stackoverflow.com/a/27944947/127971 Unfortunately, the question is not specific enough for a single answer.

@michael that answer is about importing Python modules in the general case; the dunder init.py file is needed when the interpreter searches directories for modules to import, notebook or not. The above answer about the notebook interpreter working directory and setting PYTHONPATH is correct.

I did say there were going to be multiple correct answers, due to the wording of the question. I'm not implying this answer isn't correct. But if using jupyter-notebook, you're just going to touch the file __init_.py, right? ...and, not going to want to modify PYTHONPATH nor call sys.path.append, even if they are also correct (correct?). I mean, I have dozens of directories w/ code in them, and I'm not going to add them all to the path -- or expect other users to their jupyter config file, even if it's one directory.

ipython - "ImportError: No module named" when trying to run Python scr...

python ipython jupyter-notebook importerror
Rectangle 27 86

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run

import os
os.getcwd()

However, let's say you're using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.

PSA: if you've come to this SO question because you're getting this error in jupyter-notebook, then see below, stackoverflow.com/a/27944947/127971 Unfortunately, the question is not specific enough for a single answer.

@michael that answer is about importing Python modules in the general case; the dunder init.py file is needed when the interpreter searches directories for modules to import, notebook or not. The above answer about the notebook interpreter working directory and setting PYTHONPATH is correct.

I did say there were going to be multiple correct answers, due to the wording of the question. I'm not implying this answer isn't correct. But if using jupyter-notebook, you're just going to touch the file __init_.py, right? ...and, not going to want to modify PYTHONPATH nor call sys.path.append, even if they are also correct (correct?). I mean, I have dozens of directories w/ code in them, and I'm not going to add them all to the path -- or expect other users to their jupyter config file, even if it's one directory.

ipython - "ImportError: No module named" when trying to run Python scr...

python ipython jupyter-notebook importerror
Rectangle 27 36

The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example

>>> from math import *
>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0

This practice (of importing * into the current namespace) is however discouraged

  • provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import)
  • may be inefficient, if the number of objects imported is big.
  • doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code)

Typically we therefore limit this import * practice to ad-hoc tests and the like, and instead:

explicitly import a few objects only

>>>from math import pi
>>>pi
>>>3.141592653589793
>>> sin(pi/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined

or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times)

>>>import math
  >>>math.pi
  >>>3.141592653589793
  etc..


  >>>import math as m  #bad example math being so short and standard...
  >>>m.pi
  >>>3.141592653589793
  etc..

See the Python documentation on this topic

(a) Specifically, what gets imported with from xyz import * if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with one underscore.

The advantage of from X import * is that it allows you to be lazy. The problem of it is that it will bite you in the ass for lazy :)

Some modules (like pygame, but many others) have a special submodule that is intended to be imported as *. Such special modules usually have commonly used constants or functions.

So basically I can import everything without getting a name space collision if i use import math as opposed to from math import* ?

@the_prole Indeed. import math ensures that there would be no name conflicts; to access any method or object from math in the code you will however need to prefix it with math. as in math.pi or math.sin(...). With the from math import * there will be no need for the math. prefix (in fact that would work) but on the other there may be namespace collisions.

python - What exactly does "import *" import? - Stack Overflow

python namespaces python-import
Rectangle 27 36

The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example

>>> from math import *
>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0

This practice (of importing * into the current namespace) is however discouraged

  • provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import)
  • may be inefficient, if the number of objects imported is big.
  • doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code)

Typically we therefore limit this import * practice to ad-hoc tests and the like, and instead:

explicitly import a few objects only

>>>from math import pi
>>>pi
>>>3.141592653589793
>>> sin(pi/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined

or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times)

>>>import math
  >>>math.pi
  >>>3.141592653589793
  etc..


  >>>import math as m  #bad example math being so short and standard...
  >>>m.pi
  >>>3.141592653589793
  etc..

See the Python documentation on this topic

(a) Specifically, what gets imported with from xyz import * if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with one underscore.

The advantage of from X import * is that it allows you to be lazy. The problem of it is that it will bite you in the ass for lazy :)

Some modules (like pygame, but many others) have a special submodule that is intended to be imported as *. Such special modules usually have commonly used constants or functions.

So basically I can import everything without getting a name space collision if i use import math as opposed to from math import* ?

@the_prole Indeed. import math ensures that there would be no name conflicts; to access any method or object from math in the code you will however need to prefix it with math. as in math.pi or math.sin(...). With the from math import * there will be no need for the math. prefix (in fact that would work) but on the other there may be namespace collisions.

python - What exactly does "import *" import? - Stack Overflow

python namespaces python-import
Rectangle 27 4

It looks like you are running your app with python 2.x, but the modules your app uses are from python 3.x. In particular, pymongo is trying to import the module urllib.parse, which was called urlparse in python 2.x. As a result, executing import urllib.parse with python 2.x causes an ImportError.

That's fine. The pymongo code inside your virtual env is what connects to your mongodb server (using a specified port).

After installation of Flask and pymongo I deactivated virtual environment.

Have you followed the instructions in the Flask docs with regards to mod_wsgi, virtualenv, and setting the activate_this variable?

My web-site works in a static mode, only when I start using database it stops working due to this problem with parse module

Yes, your site works fine while being executed with python 2.x, but when you start using the db, you are using modules that try to import libraries inside python 3.x. As a result, if you continue to use python 2.x to execute your site, then you are not going to be using a db.

I could not figure out what I need to put inside activate_this.py.

$ cd /some/path/to/venv

2) List all the files:

$ ls

3) Change into the bin directory:

$ cd bin

4) List all the files:

$ ls

5) Open the file activate_this.py and read the comments at the top, e.g.

$ vi activate_this.py

6) Click on the link to the Flash docs I posted in my previous response and read the material there again.

Thank you for suggestion! Yes, I do have both Python 2.7.8 and 3.4.2 on the server which causes issues. However, Python 3.4.2 is used for virtual environment and Flask and pymongo installed for virtual environment called venv. I used "source venv/bin/activate". I installed pymongo using pip3 (Python 3.4.2). I think I did not use virtual environment to install Mongodb. After installation of Flask and pymongo I deactivated virtual environment.

When I run python -V, I used to get Python 2.7.8. Now I managed to switch to Python 3.4.2, which I hoped would solve the issue that I am running Flask on 2.7.8, but apparently it's still a problem as I am "no module named parse". It seems like Flask is still being run on 2.7.8.

python - ImportError: No module named parse - Stack Overflow

python mongodb python-3.x flask pymongo
Rectangle 27 1

You have a package named platform but you are attempting to execute a script in it. When you do that, the script is going to be run independently, with none of the package information because the script is not imported. To do a proper import and then run as a script, use the -m option:

This will import the script from the platform package, set up the dependencies correctly, etc.

Generally, you would want to place your executable script outside your main package for this exact reason. If you modify your folder structure to look like this, the command python app.py should run just fine because platform will be a recognized package:

Finally, as a minor nitpick, if you do decide to keep app.py at the package level rather than the project level, I would recommend using relative imports to get the settings:

from . import settings
python -m platform.app
python platform\app.py
def main()
ImportError: cannot import name 'settings'
app.run(debug=settings.FLASK_DEBUG)
app.run()

@AnD, where is ` main ` and what does the import look like. please post that code in your question

settings.FLASK_DEBUG

python - ImportError: cannot import name 'foo' - Stack Overflow

python
Rectangle 27 20

Your code isn't compatible with the version of Django you are using.

simplejson
django.utils

Since Django 1.5 drops support for Python 2.5, we can now rely on the json module being available in Pythons standard library, so weve removed our own copy of simplejson. You should now import json instead of django.utils.simplejson.

Unfortunately, this change might have unwanted side-effects, because of incompatibilities between versions of simplejson see the backwards-incompatible changes section. If you rely on features added to simplejson after it became Pythons json, you should import simplejson explicitly.

You should update the code in extdirect's providers.py to import json instead, or use the version of Django it was designed to work with.

can i install Django version 1.5 to solve this problem?

@TameenMalik Yes, pip install django==1.5.12. However, note that Django 1.5 isn't supported anymore. You should really consider updating your code to work with a newer version of Django.

import simplejson
from django.utils import simplejson

@guival if you can update the code, then you might as well use the json module (this is already in the answer).

python - Cannot import name simplejson - After installing simplejson -...

python django
Rectangle 27 1

# Various imports, whatever, using normal sys.path, for example:
import os, sys, re, time, random
import subprocess, psutil

# Save sys.path
sys_path_saved = sys.path

# Limit sys.path for PySide import
sys.path = ['c:\\python27\\lib\\site-packages']

# PySide imports with limited sys.path
from PySide        import QtGui, QtCore
from PySide.QtGui  import QApplication, QLineEdit
from PySide.QtCore import QSettings, Qt

# Reset sys.path to original
sys.path = sys_path_saved

# Remainder of code...

Pyinstaller 1.5.1 should do a fine job of locating dependencies, and often does. However, all of many many attempts to use its pathex or hiddenimports in .spec failed. Modifying my environment variables also failed. Extracting various module files manually from from .egg sometimes worked.

However for PySide imports, the sys.path temporary limitation above was the workaround that worked.

Update: Unfortunately the exe only works on a machine with Python/Pyside installed, doesn't work on XP without Python.

pyside - Pyinstaller: ImportError: cannot import name QtGui - Stack Ov...

pyside pyinstaller
Rectangle 27 1

# Various imports, whatever, using normal sys.path, for example:
import os, sys, re, time, random
import subprocess, psutil

# Save sys.path
sys_path_saved = sys.path

# Limit sys.path for PySide import
sys.path = ['c:\\python27\\lib\\site-packages']

# PySide imports with limited sys.path
from PySide        import QtGui, QtCore
from PySide.QtGui  import QApplication, QLineEdit
from PySide.QtCore import QSettings, Qt

# Reset sys.path to original
sys.path = sys_path_saved

# Remainder of code...

Pyinstaller 1.5.1 should do a fine job of locating dependencies, and often does. However, all of many many attempts to use its pathex or hiddenimports in .spec failed. Modifying my environment variables also failed. Extracting various module files manually from from .egg sometimes worked.

However for PySide imports, the sys.path temporary limitation above was the workaround that worked.

Update: Unfortunately the exe only works on a machine with Python/Pyside installed, doesn't work on XP without Python.

pyside - Pyinstaller: ImportError: cannot import name QtGui - Stack Ov...

pyside pyinstaller
Rectangle 27 3

The problem is that the script you are writing in has the same name as the module you are importing. Change your script name to something other than bs4.py and remove the bs4.pyc:

monty-macbook:~ monty$ python bs4.py
Traceback (most recent call last):
  File "bs4.py", line 2, in <module>
    from bs4 import BeautifulSoup
  File "/Users/monty/bs4.py", line 2, in <module>
    from bs4 import BeautifulSoup
ImportError: cannot import name BeautifulSoup
monty-macbook:~ monty$ mv bs4.py bs4new.py
monty-macbook:~ monty$ rm bs4.pyc
monty-macbook:~ monty$ python bs4new.py
/Library/Python/2.7/site-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "html.parser")

  markup_type=markup_type))

python - Import error using BeautifulSoup - Stack Overflow

python beautifulsoup python-import
Rectangle 27 2

Here's a Python 3 version of the code in my other answer. It's almost identical except for the imports which had to be changed in order to use the pillow fork of the PIL (because only it supports Python 3). The other changes I made were changing print statements into function calls and where the map() function is used to create the luts look-up table variable.

from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale

def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component
                                                      # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)

if __name__ == '__main__':
    import os
    import sys

    input_image_path = 'Dn3CeZB.png'
    print('tinting "{}"'.format(input_image_path))

    root, ext = os.path.splitext(input_image_path)
    suffix = '_result_py{}'.format(sys.version_info[0])
    result_image_path = root+suffix+ext

    print('creating "{}"'.format(result_image_path))
    result = image_tint(input_image_path, '#383D2D')
    if os.path.exists(result_image_path):  # delete any previous result file
        os.remove(result_image_path)
    result.save(result_image_path)  # file name's extension determines format

    print('done')

Here's before and after images. The test image and tint color are the same as what you said you were using when you encountered the problem. The results look very similar to the Py2 version, to yours, and OK to me...am I missing something?

I will try your converted code tomorrow as I currently don't have access to my machine, thank you for converting it. In the meantime, here is another example on the bug I posted in comments above, but forgot to mention your username: i.imgur.com/YIUuTmO.png

OK, I think I see why. Does this only regulates the colour of this picture, but not the contrast and brightness of it? If so, that's not a problem, I can just add in two extra sliders.

It tries to preserve luminosity which is difficult to do when you tint with such a dark blue color (the human eye is least sensitive to blue). What's shown in the i.imgur.com/YIUuTmO.png screenshot are the results I would expect using such a dark tint color. Another way to think about what it does is it will turn white in the original image into the tint color and everything else would come out being no brighter than than.

It would be easier and faster to lighten the tint color than adjust the contrast and brightness of the whole image afterwards.

Yes, thanks. I updated my answer so it now uses tuples instead of lists when creating the main look-up table because they're smaller and accessed more quickly I believe. The function creates big one of composed of 3 to 4 256 entry tuples each time it's called and they're all local variables which should be released and garbage collected automatically when it returns--along with a temporary b&w version of the image that's also created. It will be interesting to see what if any affect there is from the modification with respect to the increasing list object count issue you mentioned.

python 3.x - Changing colour of an image - Stack Overflow

image python-3.x colors pillow wand
Rectangle 27 6

Another cause of this problem is that you can't name your application the same as another python module. For example I called mine site, little realising that site is already a python module.

You can check this by starting python, and running import site, help(site), and it will show you it isn't using your module. This of course gives you errors when django tries to import site.settings which doesn't exist.

python - How do I stop getting ImportError: Could not import settings ...

python django apache wsgi
Rectangle 27 1

I get an invalid syntax error when doing import ..abc and a Attempted relative import error if I try to from ..abc import testfunc.

The second syntax is the right one for relative imports I was a bit too fast to answer. I use it, but in deployed modules. I believe it does not work if you try to run python file directly from command line.

python - How do you import a module on one level higher? - Stack Overf...

python
Rectangle 27 1

I get an invalid syntax error when doing import ..abc and a Attempted relative import error if I try to from ..abc import testfunc.

The second syntax is the right one for relative imports I was a bit too fast to answer. I use it, but in deployed modules. I believe it does not work if you try to run python file directly from command line.

python - How do you import a module on one level higher? - Stack Overf...

python
Rectangle 27 26

from whatever import * is not a good idiom to use in your code -- it's intended for use, if ever, in an interactive session as a shortcut to save some typing. It basically "snapshots" all names from the module at that point in time -- if you ever rebind any of those names, the snapshot will have grown stale and all sort of problems will ensue. And that's only the beginning of the inextricable mess you're signing up for by using the wretched from ... import * construct.

Want my advice? Forget you ever heard about that construct existing and never, ever use it again. Use import global_mod as m and always use thereafter qualified names such as m.x -- qualified names are so much handier and more powerful in Python, than mere barenames, that it ain't even funny. (The as m part of the import statement is totally optional and basically exists for conciseness purposes, or sometimes to work around some issues with name clashes; use it when and if you find it handy, since it has no downsides, but don't feel forced or even urged to use if when you don't feel it's necessary).

scope - Python: Sharing global variables between modules and classes t...

python scope global-variables module