ImportError: cannot import name - python

I got a library called google-translate-python. https://github.com/terryyin/google-translate-python
Basically, I copied/pasted the translate.py file to my python27/lib directory. I imported it like so:
from translate import Translator
And I put in something like this:
theTranslate = Translator(to_lang="sp")
translation = theTranslate.translate("hello")
And I'm using pycharm btw so I haven't gotten any errors, it is saying the methods are there and everything.
However, I get the error: ImportError: cannot import name Translator
Did I import the library wrong? that's all I can think of. Because the methods are there and running.

I figured it out... the library I was trying to import had the same name as my actual python file. So my python file was called translate.py and my library I was trying to import was called translate. I don't know how to differentiate it.. but changing the name of my python file fixed it. wow.. that took about 3 hours to realize.

Does it show in the list of packages installed under Pycharm interpreter? You need to add the package to this list and then it becomes available to you for import. It is available as one of the packages there.

Based on the github page the package can be installed from the source using:
python setup.py install
Another option is to save the translate.py to the local directory or another directory.
If translate.py is not in the local directory you can add the module path using:
sys.path.append('PATH_TO_TRANSLATE.PY')

If you can't use pip the simplest way to get this installed would be to do download the source code (.zip file) and unzip it.
Open a terminal (where you have access to python) and change to the folder (cd <the path to the folder>) you have unzipped, and then run:
python setup.py install
This will make sure the files end up in the right location (which on Windows is actually in C:\Python27\Lib\site-packages).

Related

Using PYTHONPATH in Spyder with no access to command line

I've just started using Python with Spyder at work, which means I'm far more restricted than normal as I have no access to the command line.
I'm trying to access the PyPDF2 library, which I have downloaded as a ZIP file, and then pointed to this file with the PYTHONPATH manager. I still can't access it:
from PyPDF2 import PdfFileMerger, PdfFileReader
gets: "ImportError: No module named 'PyPDF2'"
All the walk throughs I've seen of using PYTHONPATH involve using the command line. Can anyone help with how to do this without this access? Sorry am relatively new to this and really stuck!
Thanks
I don't know anything about Spyder, but in Anaconda there is a way to install packages from the Anaconda Navigator. If Spyder doesn't have this feature, you can do the following:
Create a folder somewhere called PyPDFPath
Unzip PyPDF2 into this directory, making sure your directory structure looks like this, with all of the PyPDF2 code inside the PyPDF2 directory
At the top of your script, before any other imports, add the following code, where PYPDFPATH is the location of the PyPDFPath folder
import sys
sys.path.append('PYPDFPATH')
In your script, try importing PyPDF2 as you did in your question. If you've done everything right, you should have no problems.
The sys.path variable is a list that contains all of the folders that Python should look for modules. If you add a folder to this list with modules you'd like to import in it before you import them, Python will look for those modules in this folder in addition to the default folders it looks for modules in.
Note that if you downloaded the PyPDF2 zip from GitHub, your PyPDF2 directory needs to contain the PyPDF2 directory from inside the zip instead of the entire repository.
I hope this helps!

Python import library from tar.gz?

I am working on a box which I don't have root access. However, there is a folder /share which would be accessed for everyone to read and write.
I want to figure out a way to put python libraries so that everyone could access and use them.
I figured out that I can put the egg file in the /share/pythonLib folder and in the python script.
import sys
sys.path.append("/share/pythonLib/foo.egg")
import foo
and it would work for everyone, however, I am not sure every library has egg version. For example, I am trying to install BeautifulSoup4 , however, there is only tar.gz file and I am not sure if it would be possible to convert to egg and ..etc.
OR! I am wrong right at the BEGINNING, and there are indeed some pythonic magics like below:
magicadd /share/pythonLib/foo.tar.gz
import foo
tar.gz is the source code of the library. You should unpack it, and you will find a setup.py script inside. Run:
python setup.py install --prefix=/share/pythonLib
This will create:
/share/pythonLib/lib/python2.7/site-packages/
In your scripts append that path to sys.path and everything should work fine.

Installing pytesser

I'm new to python and would like to install and use the pytesser OCR library. All of the other modules that I've installed, I've used easy_install, which has worked fine. But pytesser is the first that I've had to install by hand using Google Code's .zip file.
Per the instructions in the readme (https://code.google.com/p/pytesser/wiki/README) I extracted the contexts to my C:\Python27\Scripts file. However when I try:
from pytesser import *
within the Python Shell, I get the following error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
from pytesser import *
ImportError: No module named pytesser
Any ideas? Windows 7. Python 2.7. My other scripts using modules such as PIL, Scrapy, Numpy have been working fine.
Thanks,
Tom
I'm not sure if this is the ideal solution, but this works for me. Please do correct me if this is incorrect in any way.
Unzip the folder & paste it in your Python2x\Lib folder
Rename it to pytesser (I'm not too sure if this is a necessary step)
Duplicate the tesseract.py file and rename it as __init__.py
Open __init__.py
Change the line tesseract_exe_name = "tesseract" to
tesseract_exe_name = 'C:\Python27\Lib\pytesser\tesseract'
Done.
You should not use C:\Python27\Scripts for 3rd party modules, you should use C:\Python27\Lib\site-packages instead.
So I'm using w10 64 bits.
And it took me some time to understand how you have to install it to be able to use it.
How to :
https://code.google.com/archive/p/pytesser/downloads
download pytesser_v0.0.1.zip
unzip
move files in the project
rename import Image to "from PIL import Image" in the pytesser.py
=== Enjoy.
Further to Yaitzme answer - another fix you may need (I'm using Python Tools for Visual Studio on Windows 7 64-bit)...
Once I renamed the pytesser.py file to __init__ I had to put a double backslash in the line e.g.
tesseract_exe_name = ‘C:\Anaconda2\Lib\site-packages\pytesser\\tesseract’
as the single backslash '\tesseract' was interpreting the '\t' as a new tab symbol and breaking the path! Put my install instructions here
I suspect the problem is with Python not being able to find your C:\Python27\Scripts directory because it's not in your PYTHONPATH.
Python looks in certain directories for files when you run an import command, they're described here http://docs.python.org/2/tutorial/modules.html#the-module-search-path
Your main options are:
1) Tell Python to look in your Scripts folder. This involves adding the folder to your Python path, see here How to add to the pythonpath in windows 7?
2) Put your script in a folder which is already searched by Python. This is wRAR's answer, to use the standard Python 3rd-party modules directory, see here http://docs.python.org/2/install/index.html#how-installation-works
3) Have the pytesser file in Python's current directory. import os followed by os.getcwd() will show you python's current directory, where the code is running (in a sense). os.chdir("my/other/dir") changes the current directory. See How to know/change current directory in Python shell? for more detail.
You may got sth wrong.
I try pytesser yesterday, maybe you should not put the pytesser file into the script folder. try the working dir, alongside with your code.
>>> import pytesser
>>> print pytesser
<module 'pytesser' from 'E:\Desktop\jiaoben\OCR\pytesser.pyc'

How do I use an external .py file?

I downloaded beautifulsoup.py for use on a little project I'm making. Do I need to import this .py file in my project?
Do I just copy and paste the code somewhere inside my current python script?
Thank you for the help.
I found this but it doesn't say anything regarding Windows.
http://mail.python.org/pipermail/tutor/2002-April/013953.html
I'm getting this error when using it. I copied and pasted the .py file to the folder where my project was on Windows Explorer, not this happens. Any suggestions?
If it's in the same directory as your little project, all you should need to do is:
import BeautifulSoup
If you are keeping it in some other directory, the easiest way to do it is:
from sys import path
path.append(path_to_Beautiful_Soup)
import BeautifulSoup
Python keeps track of where it is currently, and first looks in the current directory. Then it checks through all of the paths in sys.path for the module in question. If it cannot find it in any of those places, it throws an error.
When you install beautifulsoup the canonical way (with easy_install for example, or with a windows installer, if any) the beautifulsoup module will probably be added to your PYTHONDIR\lib\site-packages directory.
This means
import beautifulsoup
should do the trick.
Otherwise, adding beautifulsoup.py (if it's a single file) to your current project directory and then issuing import beautifulsoup should also do the trick.
You have several choices:
you can cut and paste in the code, assuming the license permits etc. however, what happens when the code is updated?
you can put the code into the same directory (ie folder) as your code. Then all you need to do is say import beautifulsoup before you try to use it.
you can put the code somewhere in the python load path.
I've done it before, putting BeautifulSoup.py inside the same directory as the script and import it would work. If you have multiple scripts spread over different directories, put the beautifulsoup file in the root directory and do a relative import.
you have to install a new package correctly in python by using in the command line:
pip install BeautifulSoup
if you don't know the name of the package use :
pip search beautiful
and the pip will get all package that have "beautiful" in their name or description ...
One more thing that is very important ; and because you use eclipse (netbeans it's the same) and pydev as i can see; you should refresh the list of package used by pydev when installing a new package by going in the menu to (for eclipse) Window -> Preference -> Pydev -> Interpreter - Python and clicking on Apply why is that ?, so that you can use the full power of pydev correctly (code completion , F3 ...) and because Pydev don't know if a package has been added until you tell him so.
the steps are for eclipse you can do their analog in netbeans right ?

Python error "ImportError: No module named"

Python is installed in a local directory.
My directory tree looks like this:
(local directory)/site-packages/toolkit/interface.py
My code is in here:
(local directory)/site-packages/toolkit/examples/mountain.py
To run the example, I write python mountain.py, and in the code I have:
from toolkit.interface import interface
And I get the error:
Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.
I do not know why Python cannot find the file when it is in sys.path. Any ideas? Can it be a permissions problem? Do I need some execution permission?
Based on your comments to orip's post, I guess this is what happened:
You edited __init__.py on windows.
The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
You used WinSCP to copy the file to your unix box.
WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."
The missing __init__.py (now called __init__.py.bin) means python doesn't understand toolkit as a package.
You create __init__.py in the appropriate directory and everything works... ?
Does
(local directory)/site-packages/toolkit
have a __init__.py?
To make import walk through your directories every directory must have a __init__.py file.
I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:
(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)
Change directory (cd) to the directory above the directory where your files are. In this case, you're trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.
When you are in the toolkit directory, enter this line of code on your command line:
export PYTHONPATH=.
This sets your PYTHONPATH to ".", which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn't just look in your current directory, but in all the directories that are in your current directory).
After you've set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.
On *nix, also make sure that PYTHONPATH is configured correctly, especially that it has this format:
.:/usr/local/lib/python
(Mind the .: at the beginning, so that it can search on the current directory, too.)
It may also be in other locations, depending on the version:
.:/usr/lib/python
.:/usr/lib/python2.6
.:/usr/lib/python2.7 and etc.
You are reading this answer says that your __init__.py is in the right place, you have installed all the dependencies and you are still getting the ImportError.
I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH didn't have the entry for the project directory. So, I set PYTHONPATH per Import statement works on PyCharm but not from terminal:
export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)
There's another way to do this using sys.path as:
import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')
You can use insert/append based on the order in which you want your project to be searched.
Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root
For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.
I solved my own problem, and I will write a summary of the things that were wrong and the solution:
The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.
Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.
To mark a directory as a package you need a file named __init__.py, does this help?
an easy solution is to install the module using python -m pip install <library-name> instead of pip install <library-name>
you may use sudo in case of admin restrictions
To all those who still have this issue. I believe Pycharm gets confused with imports. For me, when i write 'from namespace import something', the previous line gets underlined in red, signaling that there is an error, but works. However ''from .namespace import something' doesn't get underlined, but also doesn't work.
Try
try:
from namespace import something
except NameError:
from .namespace import something
Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
If you have tried all methods provided above but failed, maybe your module has the same name as a built-in module. Or, a module with the same name existing in a folder that has a high priority in sys.path than your module's.
To debug, say your from foo.bar import baz complaints ImportError: No module named bar. Changing to import foo; print foo, which will show the path of foo. Is it what you expect?
If not, Either rename foo or use absolute imports.
You must have the file __ init__.py in the same directory where it's the file that you are importing.
You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.
eg:
/etc/environment
PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2
/opt/folder1/foo
/opt/folder2/foo
And, if you are trying to import foo file, python will not know which one you want.
from foo import ... >>> importerror: no module named foo
My two cents:
Spit:
Traceback (most recent call last):
File "bash\bash.py", line 454, in main
import bosh
File "Wrye Bash Launcher.pyw", line 63, in load_module
mod = imp.load_source(fullname,filename+ext,fp)
File "bash\bosh.py", line 69, in <module>
from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
ImportError: No module named RecordGroups
This confused the hell out of me - went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python
which spit out the rather unhelpful "No module named RecordGroups". I'd be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) - have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.
EDIT (2015.01.17): I did not mention we use a custom launcher dissected here.
Fixed my issue by writing print (sys.path) and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.
In my case, because I'm using PyCharm and PyCharm create a 'venv' for every project in project folder, but it is only a mini env of python. Although you have installed the libraries you need in Python, but in your custom project 'venv', it is not available. This is the real reason of 'ImportError: No module named xxxxxx' occurred in PyCharm.
To resolve this issue, you must add libraries to your project custom env by these steps:
In PyCharm, from menu 'File'->Settings
In Settings dialog, Project: XXXProject->Project Interpreter
Click "Add" button, it will show you 'Available Packages' dialog
Search your library, click 'Install Package'
Then, all you needed package will be installed in you project custom 'venv' folder.
Enjoy.
Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages
If you're using a module compiled in C, don't forget to chmod the .so file after sudo setup.py install.
sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so
In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.
My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.
For me, running the file as a module helped.
Instead of
python myapp/app.py
using
python -m myapp.app
It's not exactly the same but it might be a better approach in some cases.
If you are using a setup script/utility (e.g. setuptools) to deploy your package, don't forget to add the respective files/modules to the installer.
When supported, use find_packages() or similar to automatically add new packages to the setup script. This will absolutely save you from a headache, especially if you put your project aside for some time and then add something later on.
import setuptools
setuptools.setup(
name="example-pkg",
version="0.0.1",
author="Example Author",
author_email="author#example.com",
description="A small example package",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
(Example taken from setuptools documentation)
I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:
Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py
In 'main.py' I had tried unsuccessfully all the combinations bellow:
from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...
The solution was much more simple than I thought. I renamed the folder "Booklet" into "booklet" and that's it. Now Python can import the class Question normally by using in 'main.py' the code:
from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass
From this I can conclude that Package-Names (folders) like 'booklet' must start from lower-case, else Python confuses it with Class names and Filenames.
Apparently, this was not your problem, but John Fouhy's answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.
In linux server try dos2unix script_name
(remove all (if there is any) pyc files with command find . -name '*.pyc' -delete)
and re run in the case if you worked on script on windows
In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.
I've found that changing the name (via GUI) of aliased folders (Mac) can cause issues with loading modules. If the original folder name is changed, remake the symbolic link. I'm unsure how prevalent this behavior may be, but it was frustrating to debug.
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
if your default python is pyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.py need python3, for this case(bs4)
you can not execute this module with python2 like this:
$ python file.py
# or
$ file.py
# or
$ file.py # if locate in $PATH
Tow way to fix this error,
# should be to make python3 as default by symlink
$ rm $(which python) && ln -s $(which python3) /usr/bin/python
# or use alias
alias python='/usr/bin.../python3'
or change shebang in file.py to
#!/usr/bin/...python3
After just suffering the same issue I found my resolution was to delete all pyc files from my project, it seems like these cached files were somehow causing this error.
Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for *.pyc, then selecting all (Ctrl+A) and deleting them (Ctrl+X).
Its possible I could have resolved my issues by just deleting the specific pyc file but I never tried this
I faced the same problem: Import error. In addition the library've been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.
I had the same error. It was caused by somebody creating a folder in the same folder as my script, the name of which conflicted with a module I was importing from elsewhere. Instead of importing the external module, it looked inside this folder which obviously didn't contain the expected modules.

Categories

Resources