Import own .py files in anaconda spyder - python

I've written my own mail.py module in spider (anaconda). I want to import this py file in other python (spider) files just by 'import mail'
I searched on the internet and couldn't find a clearly solution.

To import any python script, it should exist in the PYTHONPATH. You can check this with the following code:
import sys
print sys.path
To import your Python script:
Put both the scripts (main and the imported python script) in the
same directory.
Add the location of the file to be imported to the
sys.path.
For example, if the script is located as '/location/to/file/script.py':
import sys
sys.path.append('/location/to/file/')
import script

I had the same problem, my files were in same folder, yet it was throwing an error while importing the "to_be_imported_file.py".
I had to run the "to_be_imported_file.py" seperately before importing it to another file.
I hope it works for you too.

Searched for an answer for this question to. To use a .py file as a import module from your main folder, you need to place both files in one folder or append a path to the location. If you storage both files in one folder, then check the working directory in the upper right corner of the spyder interface. Because of the wrong working directory you will see a ModuleNotFoundError.

There are many options, e.g.
Place the mail.py file alongside the other python files (this works because the current working dir is on the PYTHONPATH.
Save a copy of mail.py in the anaconda python environment's "/lib/site-packages" folder so it will be available for any python script using that environment.

I did a slightly different solution approach that is less sophisticated. When I start my anaconda terminal it is at a C prompt. I just did a cd d:\mypython\lib in the beginning window before starting python. once I did that I could simply just import my own classes that I put in that library with "import MyClass as my" then I was off and running. It is interesting, I did 2 days of internet searching in my part time and could not find the answer either, until I asked a friend.
cd d:\mypython\lib
python
>>> import MyClass as my
>>> my1=my.MyClass()
>>> my1.doSomething()
worked for me on my anaconda / windows 10 environment python 3.6.6.

when calling any function from another file, it should be noted to not import any library inside the function

I believe the easiest solution is to place the directory containing your Python files into the Anaconda site-packages folder on your machine. I wrote an article outlining the whole process but, in short, you'll need to create a folder containing your python script and an __init__.py file. Then place that folder inside the site-packages folder in the Anaconda directory.
On Windows the site-packages directory is typically located at:
C:\Users\[your_username]\Anaconda3\Lib\site-packages\
On Mac the site-packages directory is typically located located at:
Users/[your_username]/opt/anaconda3/lib/[python3.8]/site-packages/
Notice, on Mac the Python version matters. You'll need to look for the directory that corresponds to the (base) Python version used by Anaconda. Also, anything I've placed inside of square brackets in the file paths above need to be changed according to your particular machine and Python version.
The file structure should look something like this:
~/
|__site-packages/
|__your_folder/
script.py
__init__.py
After you have the folder containing your script.py and __init__.py file moved into the site-packages subdirectory of Anaconda, you'll be able to import it from any script you run on your machine.

Related

How to solve " ImportError: No module named mechanize " [duplicate]

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.
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)
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.
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.

How to get module from another directory from terminal?

this is in Python, python 3.10.2 if we need specifics.
I’m using the Mac Terminal and I want to access a folder from it
I have a folder on my desktop that has a bunch of my modules. I wanna access these from the terminal in a style like: “import module” with using some command to get to that folder.
Help would be appreciated!
You can import sys, then sys.path.append(path_to_desired_modules). sys.path is a list of the directories where Python will search for the modules to import, so if you append the target directory to that, it should be retrievable.

ImportError: No module named channels.asgi [duplicate]

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.

How to import python file located in same subdirectory in a pycharm project

I have an input error in pycharm when debugging and running.
My project structure is rooted properly, etc./HW3/. so that HW3 is the root directory.
I have a subfolder in HW3, util, and a file, util/util.py. I have another file in util called run_tests.py.
In run_tests.py, I have the following import structure,
from util.util import my_functions, etc.
This yields an input error, from util.util import load_dataset,proportionate_sample
ImportError: No module named 'util.util'; 'util' is not a package
However, in the exact same project, in another directory (same level as util) called data, I have a file data/data_prep.py, which also imports functions from util/util.py using a similar import statement...and it runs without any problems.
Obviously, I am doing this in the course of doing a homework, so please understand: this is ancillary to the scope of the homework.
The problem goes away when I move the file to another directory. So I guess this question is How do I import a python file located in the same directory in a pycharm project? Because pycharm raises an error if I just do import util and prompts me to use the full name from the root.
Recommended Way:
Make sure to set the working folder as Sources.
You can do it in Pycharm -> Preferences -> Project: XYZ -> Project Structure
Select your working folder and mark it as Sources. Then Pycharm recognize the working folder as a Source folder for the project and you will be able to simply add other files within that folder by using
import filename.py
or
from filename.py import mudule1
=================
Not recommended way:
In Pycharmyou can simply add . before the .py file which you are going to import it from the same folder. In your case it will be
from .util import my_functions
Resource
There is a good reference also for more information with example how to implement Package Relative Imports. I would highly recommend to check this page.
Package Relative Imports
If you don't have an __init__.py create one and add this line
from util.util import my_function
then you can easily import the module in your scripts
the __init__.py tells python that it should treat that folder as a python package, it can also be used to import/load modules too.
in most cases the __init__.py is empty.
Quoting the docs:
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.
Right-click on the folder which you want to be marked as the source > Mark Directory as > Source root.
In my case, it worked only when I omit the extension. Example:
import filename
Note: May be a bit unrelated.
I was facing the same issue but I was unable to import a module in the same directory (rather than subdirectory as asked by OP) when running a jupyter notebook (here the directory didn't have __init__.py). Strangely, I had setup python path and interpreter location and everything. None of the other answers helped but changing the directory in python did.
import os
os.chdir(/path/to/your/directory/)
I'm using PyCharm 2017.3 on Ubuntu 16.04
I had the same issue with pycharm, but the actual mistake was that the file I was trying to import didn't have a .py extension, even though I was able to run it as a standalone script. Look in the explorer window and make sure it has a .py extension. If not, right click on the file in the explorer window, pick refactor, and then rename it with a .py extension.
In Pycharm go to "Run - Configuration" and uncheck
'Add Content root to Pythonpath' and
'Add source roots to Pythonpath',
then use
from filename import functionname
For me the issue was, the source directory was marked correctly, but my file to import was named starting with numeric value. Resolved by renaming it.
import 01_MyModuleToImport
to
import MyModuleToImport

Where is my Python 2.7 Module Path?

I am using a python package called kRPC that requires a basic boilerplate of setup code to use in any given instance, so here's my question:
Once I create a generic 'kRPCboilerplate.py', where can I place it inside my Python27 directory so that I can simply type,
import kRPCboilerplate
at the beginning of all my files?
I want to install my custom Python file to my Python directory so that I don't have to copy and paste the file into every new project folder I make.
I understand that,
import boilerplate
will import 'boilerplate.py', but only if 'boilerplate.py' is set in the root directory relative to the Python file that imports it.
The program I am creating will not be distributed, so there is no need to make a module installer, which is above the scope of my abilities. I simply want to copy and paste 'kRPCboilerplate.py' to the proper directory so that I can use Import without ever having to specify a path or copy and paste the imported file into the relative directory.
Your module root directory is 'Python27\Lib' where Python27 is your main python folder which includes the python executable file. You can drag and drop the .py files into there and import it without any complications!
Bit late to reply, but the safest is to set a special environmental variable called PYTHONPATH which will add search location for Python to search for libraries:
eg in Linux terminal:
export PYTHONPATH=$PYTHONPATH:/path/to/file
note it is only the path to the file, not the filename.
If you want a more permanent solution you can add
export PYTHONPATH=$PYTHONPATH:/path/to/file
to your ~/.bashrc or ~/.profile file
In windows the environmental variables are set in the config panel.
Not sure about OSx

Categories