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?
alex
6,3409 gold badges50 silver badges103 bronze badges
asked Dec 3, 2008 at 21:26
7
Based on your comments to orip’s post, I guess this is what happened:
- You edited
__init__.pyon 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__.pyin the appropriate directory and everything works… ?
answered Dec 4, 2008 at 0:17
John FouhyJohn Fouhy
40.5k19 gold badges62 silver badges77 bronze badges
8
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.
answered Dec 3, 2008 at 21:50
igorgueigorgue
17.6k13 gold badges37 silver badges52 bronze badges
2
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.pyfile, and trying to call thetoolkit.interface.pymodule, 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 thetoolkitdirectory. -
When you are in the
toolkitdirectory, 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
toolkitdirectory). Python should now find and load the modules you specified.
user
5,2146 gold badges18 silver badges35 bronze badges
answered Apr 22, 2014 at 3:52
SpecteraceSpecterace
1,0057 silver badges7 bronze badges
4
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.
answered Mar 4, 2011 at 21:14
RenaudRenaud
15.7k6 gold badges79 silver badges78 bronze badges
6
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.
jww
95.1k88 gold badges397 silver badges862 bronze badges
answered Feb 8, 2019 at 16:57
avpavp
2,76228 silver badges33 bronze badges
4
Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root
answered Jan 4, 2017 at 17:53
MonoThreadedMonoThreaded
11.2k11 gold badges69 silver badges100 bronze badges
2
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.
answered Aug 22, 2019 at 16:02
kevkev
2,6513 gold badges21 silver badges45 bronze badges
1
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.
answered Dec 4, 2008 at 1:11
EduardoEduardo
19.4k22 gold badges63 silver badges73 bronze badges
3
To mark a directory as a package you need a file named __init__.py, does this help?
answered Dec 3, 2008 at 21:31
oriporip
71.9k21 gold badges118 silver badges147 bronze badges
8
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
answered Sep 18, 2017 at 15:30
Badr BellajBadr Bellaj
10.6k2 gold badges40 silver badges40 bronze badges
3
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
answered May 11, 2019 at 19:34
AKJAKJ
8522 gold badges13 silver badges18 bronze badges
1
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.
answered Jan 7, 2009 at 14:22
miyamiya
1,0591 gold badge11 silver badges20 bronze badges
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.
answered May 2, 2017 at 6:41
liushuaikobeliushuaikobe
2,1221 gold badge23 silver badges26 bronze badges
1
- 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
answered Jan 9, 2014 at 19:45
Iasmini GomesIasmini Gomes
6671 gold badge8 silver badges14 bronze badges
0
My two cents:
Spit:
Traceback (most recent call last):
File "bashbash.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 "bashbosh.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.
answered Sep 6, 2014 at 11:17
Mr_and_Mrs_DMr_and_Mrs_D
31.2k37 gold badges175 silver badges355 bronze badges
2
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.
answered Jul 21, 2016 at 18:51
dukevindukevin
22k36 gold badges80 silver badges110 bronze badges
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.
answered Feb 18, 2019 at 3:35
YuanhuiYuanhui
4595 silver badges15 bronze badges
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
answered May 30, 2014 at 22:50
KrisWebDevKrisWebDev
9,2324 gold badges38 silver badges59 bronze badges
0
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.
answered Sep 4, 2013 at 2:52
peter karasevpeter karasev
2,5281 gold badge28 silver badges38 bronze badges
My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.
answered Mar 27, 2018 at 12:41
RichRich
6421 gold badge6 silver badges14 bronze badges
0
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)
answered Oct 17, 2020 at 11:36
michael-slxmichael-slx
6558 silver badges15 bronze badges
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.
answered Apr 28, 2022 at 13:59
juanignaciosljuanignaciosl
3,3952 gold badges26 silver badges28 bronze badges
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.
answered May 27, 2018 at 23:49
ioaniatrioaniatr
2774 silver badges15 bronze badges
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
answered Jan 17, 2020 at 15:07
PoliPoli
7710 bronze badges
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.
answered Mar 10, 2020 at 9:55
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.
answered Feb 17, 2021 at 18:47
GhotiGhoti
7374 silver badges18 bronze badges
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
- if your default
pythonispyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.pyneedpython3, for this case(bs4)- you can not execute this module with
python2like 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
answered Aug 2, 2022 at 23:05
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
sina72
4,8413 gold badges34 silver badges36 bronze badges
answered Aug 8, 2014 at 8:36
SayseSayse
42.2k14 gold badges77 silver badges143 bronze badges
0
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.
answered Dec 5, 2015 at 7:21
RocketqRocketq
5,02420 gold badges75 silver badges123 bronze badges
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.
answered Dec 13, 2016 at 11:45
Toivo SäwénToivo Säwén
1,6732 gold badges14 silver badges33 bronze badges
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?
alex
6,3409 gold badges50 silver badges103 bronze badges
asked Dec 3, 2008 at 21:26
7
Based on your comments to orip’s post, I guess this is what happened:
- You edited
__init__.pyon 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__.pyin the appropriate directory and everything works… ?
answered Dec 4, 2008 at 0:17
John FouhyJohn Fouhy
40.5k19 gold badges62 silver badges77 bronze badges
8
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.
answered Dec 3, 2008 at 21:50
igorgueigorgue
17.6k13 gold badges37 silver badges52 bronze badges
2
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.pyfile, and trying to call thetoolkit.interface.pymodule, 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 thetoolkitdirectory. -
When you are in the
toolkitdirectory, 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
toolkitdirectory). Python should now find and load the modules you specified.
user
5,2146 gold badges18 silver badges35 bronze badges
answered Apr 22, 2014 at 3:52
SpecteraceSpecterace
1,0057 silver badges7 bronze badges
4
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.
answered Mar 4, 2011 at 21:14
RenaudRenaud
15.7k6 gold badges79 silver badges78 bronze badges
6
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.
jww
95.1k88 gold badges397 silver badges862 bronze badges
answered Feb 8, 2019 at 16:57
avpavp
2,76228 silver badges33 bronze badges
4
Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root
answered Jan 4, 2017 at 17:53
MonoThreadedMonoThreaded
11.2k11 gold badges69 silver badges100 bronze badges
2
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.
answered Aug 22, 2019 at 16:02
kevkev
2,6513 gold badges21 silver badges45 bronze badges
1
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.
answered Dec 4, 2008 at 1:11
EduardoEduardo
19.4k22 gold badges63 silver badges73 bronze badges
3
To mark a directory as a package you need a file named __init__.py, does this help?
answered Dec 3, 2008 at 21:31
oriporip
71.9k21 gold badges118 silver badges147 bronze badges
8
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
answered Sep 18, 2017 at 15:30
Badr BellajBadr Bellaj
10.6k2 gold badges40 silver badges40 bronze badges
3
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
answered May 11, 2019 at 19:34
AKJAKJ
8522 gold badges13 silver badges18 bronze badges
1
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.
answered Jan 7, 2009 at 14:22
miyamiya
1,0591 gold badge11 silver badges20 bronze badges
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.
answered May 2, 2017 at 6:41
liushuaikobeliushuaikobe
2,1221 gold badge23 silver badges26 bronze badges
1
- 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
answered Jan 9, 2014 at 19:45
Iasmini GomesIasmini Gomes
6671 gold badge8 silver badges14 bronze badges
0
My two cents:
Spit:
Traceback (most recent call last):
File "bashbash.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 "bashbosh.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.
answered Sep 6, 2014 at 11:17
Mr_and_Mrs_DMr_and_Mrs_D
31.2k37 gold badges175 silver badges355 bronze badges
2
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.
answered Jul 21, 2016 at 18:51
dukevindukevin
22k36 gold badges80 silver badges110 bronze badges
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.
answered Feb 18, 2019 at 3:35
YuanhuiYuanhui
4595 silver badges15 bronze badges
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
answered May 30, 2014 at 22:50
KrisWebDevKrisWebDev
9,2324 gold badges38 silver badges59 bronze badges
0
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.
answered Sep 4, 2013 at 2:52
peter karasevpeter karasev
2,5281 gold badge28 silver badges38 bronze badges
My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.
answered Mar 27, 2018 at 12:41
RichRich
6421 gold badge6 silver badges14 bronze badges
0
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)
answered Oct 17, 2020 at 11:36
michael-slxmichael-slx
6558 silver badges15 bronze badges
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.
answered Apr 28, 2022 at 13:59
juanignaciosljuanignaciosl
3,3952 gold badges26 silver badges28 bronze badges
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.
answered May 27, 2018 at 23:49
ioaniatrioaniatr
2774 silver badges15 bronze badges
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
answered Jan 17, 2020 at 15:07
PoliPoli
7710 bronze badges
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.
answered Mar 10, 2020 at 9:55
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.
answered Feb 17, 2021 at 18:47
GhotiGhoti
7374 silver badges18 bronze badges
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
- if your default
pythonispyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.pyneedpython3, for this case(bs4)- you can not execute this module with
python2like 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
answered Aug 2, 2022 at 23:05
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
sina72
4,8413 gold badges34 silver badges36 bronze badges
answered Aug 8, 2014 at 8:36
SayseSayse
42.2k14 gold badges77 silver badges143 bronze badges
0
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.
answered Dec 5, 2015 at 7:21
RocketqRocketq
5,02420 gold badges75 silver badges123 bronze badges
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.
answered Dec 13, 2016 at 11:45
Toivo SäwénToivo Säwén
1,6732 gold badges14 silver badges33 bronze badges
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?
alex
6,3409 gold badges50 silver badges103 bronze badges
asked Dec 3, 2008 at 21:26
7
Based on your comments to orip’s post, I guess this is what happened:
- You edited
__init__.pyon 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__.pyin the appropriate directory and everything works… ?
answered Dec 4, 2008 at 0:17
John FouhyJohn Fouhy
40.5k19 gold badges62 silver badges77 bronze badges
8
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.
answered Dec 3, 2008 at 21:50
igorgueigorgue
17.6k13 gold badges37 silver badges52 bronze badges
2
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.pyfile, and trying to call thetoolkit.interface.pymodule, 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 thetoolkitdirectory. -
When you are in the
toolkitdirectory, 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
toolkitdirectory). Python should now find and load the modules you specified.
user
5,2146 gold badges18 silver badges35 bronze badges
answered Apr 22, 2014 at 3:52
SpecteraceSpecterace
1,0057 silver badges7 bronze badges
4
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.
answered Mar 4, 2011 at 21:14
RenaudRenaud
15.7k6 gold badges79 silver badges78 bronze badges
6
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.
jww
95.1k88 gold badges397 silver badges862 bronze badges
answered Feb 8, 2019 at 16:57
avpavp
2,76228 silver badges33 bronze badges
4
Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root
answered Jan 4, 2017 at 17:53
MonoThreadedMonoThreaded
11.2k11 gold badges69 silver badges100 bronze badges
2
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.
answered Aug 22, 2019 at 16:02
kevkev
2,6513 gold badges21 silver badges45 bronze badges
1
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.
answered Dec 4, 2008 at 1:11
EduardoEduardo
19.4k22 gold badges63 silver badges73 bronze badges
3
To mark a directory as a package you need a file named __init__.py, does this help?
answered Dec 3, 2008 at 21:31
oriporip
71.9k21 gold badges118 silver badges147 bronze badges
8
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
answered Sep 18, 2017 at 15:30
Badr BellajBadr Bellaj
10.6k2 gold badges40 silver badges40 bronze badges
3
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
answered May 11, 2019 at 19:34
AKJAKJ
8522 gold badges13 silver badges18 bronze badges
1
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.
answered Jan 7, 2009 at 14:22
miyamiya
1,0591 gold badge11 silver badges20 bronze badges
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.
answered May 2, 2017 at 6:41
liushuaikobeliushuaikobe
2,1221 gold badge23 silver badges26 bronze badges
1
- 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
answered Jan 9, 2014 at 19:45
Iasmini GomesIasmini Gomes
6671 gold badge8 silver badges14 bronze badges
0
My two cents:
Spit:
Traceback (most recent call last):
File "bashbash.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 "bashbosh.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.
answered Sep 6, 2014 at 11:17
Mr_and_Mrs_DMr_and_Mrs_D
31.2k37 gold badges175 silver badges355 bronze badges
2
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.
answered Jul 21, 2016 at 18:51
dukevindukevin
22k36 gold badges80 silver badges110 bronze badges
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.
answered Feb 18, 2019 at 3:35
YuanhuiYuanhui
4595 silver badges15 bronze badges
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
answered May 30, 2014 at 22:50
KrisWebDevKrisWebDev
9,2324 gold badges38 silver badges59 bronze badges
0
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.
answered Sep 4, 2013 at 2:52
peter karasevpeter karasev
2,5281 gold badge28 silver badges38 bronze badges
My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.
answered Mar 27, 2018 at 12:41
RichRich
6421 gold badge6 silver badges14 bronze badges
0
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)
answered Oct 17, 2020 at 11:36
michael-slxmichael-slx
6558 silver badges15 bronze badges
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.
answered Apr 28, 2022 at 13:59
juanignaciosljuanignaciosl
3,3952 gold badges26 silver badges28 bronze badges
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.
answered May 27, 2018 at 23:49
ioaniatrioaniatr
2774 silver badges15 bronze badges
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
answered Jan 17, 2020 at 15:07
PoliPoli
7710 bronze badges
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.
answered Mar 10, 2020 at 9:55
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.
answered Feb 17, 2021 at 18:47
GhotiGhoti
7374 silver badges18 bronze badges
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
- if your default
pythonispyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.pyneedpython3, for this case(bs4)- you can not execute this module with
python2like 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
answered Aug 2, 2022 at 23:05
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
sina72
4,8413 gold badges34 silver badges36 bronze badges
answered Aug 8, 2014 at 8:36
SayseSayse
42.2k14 gold badges77 silver badges143 bronze badges
0
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.
answered Dec 5, 2015 at 7:21
RocketqRocketq
5,02420 gold badges75 silver badges123 bronze badges
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.
answered Dec 13, 2016 at 11:45
Toivo SäwénToivo Säwén
1,6732 gold badges14 silver badges33 bronze badges
Python выводит трассировку (далее traceback), когда в вашем коде появляется ошибка. Вывод traceback может быть немного пугающим, если вы видите его впервые, или не понимаете, чего от вас хотят. Однако traceback Python содержит много информации, которая может помочь вам определить и исправить причину, из-за которой в вашем коде возникла ошибка.
Содержание статьи
- Traceback — Что это такое и почему оно появляется?
- Как правильно читать трассировку?
- Обзор трассировка Python
- Подробный обзор трассировки в Python
- Обзор основных Traceback исключений в Python
- AttributeError
- ImportError
- IndexError
- KeyError
- NameError
- SyntaxError
- TypeError
- ValueError
- Логирование ошибок из Traceback
- Вывод
Понимание того, какую информацию предоставляет traceback Python является основополагающим критерием того, как стать лучшим Python программистом.
К концу данной статьи вы сможете:
- Понимать, что несет за собой traceback
- Различать основные виды traceback
- Успешно вести журнал traceback, при этом исправить ошибку
Python Traceback — Как правильно читать трассировку?
Traceback (трассировка) — это отчет, который содержит вызовы выполненных функций в вашем коде в определенный момент.
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
Traceback называют по разному, иногда они упоминаются как трассировка стэка, обратная трассировка, и так далее. В Python используется определение “трассировка”.
Когда ваша программа выдает ошибку, Python выводит текущую трассировку, чтобы подсказать вам, что именно пошло не так. Ниже вы увидите пример, демонстрирующий данную ситуацию:
|
def say_hello(man): print(‘Привет, ‘ + wrong_variable) say_hello(‘Иван’) |
Здесь say_hello() вызывается с параметром man. Однако, в say_hello() это имя переменной не используется. Это связано с тем, что оно написано по другому: wrong_variable в вызове print().
Обратите внимание: в данной статье подразумевается, что вы уже имеете представление об ошибках Python. Если это вам не знакомо, или вы хотите освежить память, можете ознакомиться с нашей статьей: Обработка ошибок в Python
Когда вы запускаете эту программу, вы получите следующую трассировку:
|
Traceback (most recent call last): File «/home/test.py», line 4, in <module> say_hello(‘Иван’) File «/home/test.py», line 2, in say_hello print(‘Привет, ‘ + wrong_variable) NameError: name ‘wrong_variable’ is not defined Process finished with exit code 1 |
Эта выдача из traceback содержит массу информации, которая вам понадобится для определения проблемы. Последняя строка трассировки говорит нам, какой тип ошибки возник, а также дополнительная релевантная информация об ошибке. Предыдущие строки из traceback указывают на код, из-за которого возникла ошибка.
В traceback выше, ошибкой является NameError, она означает, что есть отсылка к какому-то имени (переменной, функции, класса), которое не было определено. В данном случае, ссылаются на имя wrong_variable.
Последняя строка содержит достаточно информации для того, чтобы вы могли решить эту проблему. Поиск переменной wrong_variable, и заменит её атрибутом из функции на man. Однако, скорее всего в реальном случае вы будете иметь дело с более сложным кодом.
Python Traceback — Как правильно понять в чем ошибка?
Трассировка Python содержит массу полезной информации, когда вам нужно определить причину ошибки, возникшей в вашем коде. В данном разделе, мы рассмотрим различные виды traceback, чтобы понять ключевые отличия информации, содержащейся в traceback.
Существует несколько секций для каждой трассировки Python, которые являются крайне важными. Диаграмма ниже описывает несколько частей:
В Python лучше всего читать трассировку снизу вверх.
- Синее поле: последняя строка из traceback — это строка уведомления об ошибке. Синий фрагмент содержит название возникшей ошибки.
- Зеленое поле: после названия ошибки идет описание ошибки. Это описание обычно содержит полезную информацию для понимания причины возникновения ошибки.
- Желтое поле: чуть выше в трассировке содержатся различные вызовы функций. Снизу вверх — от самых последних, до самых первых. Эти вызовы представлены двухстрочными вводами для каждого вызова. Первая строка каждого вызова содержит такую информацию, как название файла, номер строки и название модуля. Все они указывают на то, где может быть найден код.
- Красное подчеркивание: вторая строка этих вызовов содержит непосредственный код, который был выполнен с ошибкой.
Есть ряд отличий между выдачей трассировок, когда вы запускает код в командной строке, и между запуском кода в REPL. Ниже вы можете видеть тот же код из предыдущего раздела, запущенного в REPL и итоговой выдачей трассировки:
|
Python 3.7.4 (default, Jul 16 2019, 07:12:58) [GCC 9.1.0] on linux Type «help», «copyright», «credits» or «license» for more information. >>> >>> >>> def say_hello(man): ... print(‘Привет, ‘ + wrong_variable) ... >>> say_hello(‘Иван’) Traceback (most recent call last): File «<stdin>», line 1, in <module> File «<stdin>», line 2, in say_hello NameError: name ‘wrong_variable’ is not defined |
Обратите внимание на то, что на месте названия файла вы увидите <stdin>. Это логично, так как вы выполнили код через стандартный ввод. Кроме этого, выполненные строки кода не отображаются в traceback.
Важно помнить: если вы привыкли видеть трассировки стэка в других языках программирования, то вы обратите внимание на явное различие с тем, как выглядит traceback в Python. Большая часть других языков программирования выводят ошибку в начале, и затем ведут сверху вниз, от недавних к последним вызовам.
Это уже обсуждалось, но все же: трассировки Python читаются снизу вверх. Это очень помогает, так как трассировка выводится в вашем терминале (или любым другим способом, которым вы читаете трассировку) и заканчивается в конце выдачи, что помогает последовательно структурировать прочтение из traceback и понять в чем ошибка.
Traceback в Python на примерах кода
Изучение отдельно взятой трассировки поможет вам лучше понять и увидеть, какая информация в ней вам дана и как её применить.
Код ниже используется в примерах для иллюстрации информации, данной в трассировке Python:
Мы запустили ниже предоставленный код в качестве примера и покажем какую информацию мы получили от трассировки.
Сохраняем данный код в файле greetings.py
|
def who_to_greet(person): return person if person else input(‘Кого приветствовать? ‘) def greet(someone, greeting=‘Здравствуйте’): print(greeting + ‘, ‘ + who_to_greet(someone)) def greet_many(people): for person in people: try: greet(person) except Exception: print(‘Привет, ‘ + person) |
Функция who_to_greet() принимает значение person и либо возвращает данное значение если оно не пустое, либо запрашивает значение от пользовательского ввода через input().
Далее, greet() берет имя для приветствия из someone, необязательное значение из greeting и вызывает print(). Также с переданным значением из someone вызывается who_to_greet().
Наконец, greet_many() выполнит итерацию по списку людей и вызовет greet(). Если при вызове greet() возникает ошибка, то выводится резервное приветствие print('hi, ' + person).
Этот код написан правильно, так что никаких ошибок быть не может при наличии правильного ввода.
Если вы добавите вызов функции greet() в конце нашего кода (которого сохранили в файл greetings.py) и дадите аргумент который он не ожидает (например, greet('Chad', greting='Хай')), то вы получите следующую трассировку:
|
$ python greetings.py Traceback (most recent call last): File «/home/greetings.py», line 19, in <module> greet(‘Chad’, greting=‘Yo’) TypeError: greet() got an unexpected keyword argument ‘greting’ |
Еще раз, в случае с трассировкой Python, лучше анализировать снизу вверх. Начиная с последней строки трассировки, вы увидите, что ошибкой является TypeError. Сообщения, которые следуют за типом ошибки, дают вам полезную информацию. Трассировка сообщает, что greet() вызван с аргументом, который не ожидался. Неизвестное название аргумента предоставляется в том числе, в нашем случае это greting.
Поднимаясь выше, вы можете видеть строку, которая привела к исключению. В данном случае, это вызов greet(), который мы добавили в конце greetings.py.
Следующая строка дает нам путь к файлу, в котором лежит код, номер строки этого файла, где вы можете найти код, и то, какой в нем модуль. В нашем случае, так как наш код не содержит никаких модулей Python, мы увидим только надпись , означающую, что этот файл является выполняемым.
С другим файлом и другим вводом, вы можете увидеть, что трассировка явно указывает вам на правильное направление, чтобы найти проблему. Следуя этой информации, мы удаляем злополучный вызов greet() в конце greetings.py, и добавляем следующий файл под названием example.py в папку:
|
from greetings import greet greet(1) |
Здесь вы настраиваете еще один файл Python, который импортирует ваш предыдущий модуль greetings.py, и используете его greet(). Вот что произойдете, если вы запустите example.py:
|
$ python example.py Traceback (most recent call last): File «/path/to/example.py», line 3, in <module> greet(1) File «/path/to/greetings.py», line 5, in greet print(greeting + ‘, ‘ + who_to_greet(someone)) TypeError: must be str, not int |
В данном случае снова возникает ошибка TypeError, но на этот раз уведомление об ошибки не очень помогает. Оно говорит о том, что где-то в коде ожидается работа со строкой, но было дано целое число.
Идя выше, вы увидите строку кода, которая выполняется. Затем файл и номер строки кода. На этот раз мы получаем имя функции, которая была выполнена — greet().
Поднимаясь к следующей выполняемой строке кода, мы видим наш проблемный вызов greet(), передающий целое число.
Иногда, после появления ошибки, другой кусок кода берет эту ошибку и также её выдает. В таких случаях, Python выдает все трассировки ошибки в том порядке, в котором они были получены, и все по тому же принципу, заканчивая на самой последней трассировке.
Так как это может сбивать с толку, рассмотрим пример. Добавим вызов greet_many() в конце greetings.py:
|
# greetings.py ... greet_many([‘Chad’, ‘Dan’, 1]) |
Это должно привести к выводу приветствия всем трем людям. Однако, если вы запустите этот код, вы увидите несколько трассировок в выдаче:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$ python greetings.py Hello, Chad Hello, Dan Traceback (most recent call last): File «greetings.py», line 10, in greet_many greet(person) File «greetings.py», line 5, in greet print(greeting + ‘, ‘ + who_to_greet(someone)) TypeError: must be str, not int During handling of the above exception, another exception occurred: Traceback (most recent call last): File «greetings.py», line 14, in <module> greet_many([‘Chad’, ‘Dan’, 1]) File «greetings.py», line 12, in greet_many print(‘hi, ‘ + person) TypeError: must be str, not int |
Обратите внимание на выделенную строку, начинающуюся с “During handling in the output above”. Между всеми трассировками, вы ее увидите.
Это достаточно ясное уведомление: Пока ваш код пытался обработать предыдущую ошибку, возникла новая.
Обратите внимание: функция отображения предыдущих трассировок была добавлена в Python 3. В Python 2 вы можете получать только трассировку последней ошибки.
Вы могли видеть предыдущую ошибку, когда вызывали greet() с целым числом. Так как мы добавили 1 в список людей для приветствия, мы можем ожидать тот же результат. Однако, функция greet_many() оборачивает вызов greet() и пытается в блоке try и except. На случай, если greet() приведет к ошибке, greet_many() захочет вывести приветствие по-умолчанию.
Соответствующая часть greetings.py повторяется здесь:
|
def greet_many(people): for person in people: try: greet(person) except Exception: print(‘hi, ‘ + person) |
Когда greet() приводит к TypeError из-за неправильного ввода числа, greet_many() обрабатывает эту ошибку и пытается вывести простое приветствие. Здесь код приводит к другой, аналогичной ошибке. Он все еще пытается добавить строку и целое число.
Просмотр всей трассировки может помочь вам увидеть, что стало причиной ошибки. Иногда, когда вы получаете последнюю ошибку с последующей трассировкой, вы можете не увидеть, что пошло не так. В этих случаях, изучение предыдущих ошибок даст лучшее представление о корне проблемы.
Обзор основных Traceback исключений в Python 3
Понимание того, как читаются трассировки Python, когда ваша программа выдает ошибку, может быть очень полезным навыком, однако умение различать отдельные трассировки может заметно ускорить вашу работу.
Рассмотрим основные ошибки, с которыми вы можете сталкиваться, причины их появления и что они значат, а также информацию, которую вы можете найти в их трассировках.
Ошибка AttributeError object has no attribute [Решено]
AttributeError возникает тогда, когда вы пытаетесь получить доступ к атрибуту объекта, который не содержит определенного атрибута. Документация Python определяет, когда эта ошибка возникнет:
Возникает при вызове несуществующего атрибута или присвоение значения несуществующему атрибуту.
Пример ошибки AttributeError:
|
>>> an_int = 1 >>> an_int.an_attribute Traceback (most recent call last): File «<stdin>», line 1, in <module> AttributeError: ‘int’ object has no attribute ‘an_attribute’ |
Строка уведомления об ошибке для AttributeError говорит вам, что определенный тип объекта, в данном случае int, не имеет доступа к атрибуту, в нашем случае an_attribute. Увидев AttributeError в строке уведомления об ошибке, вы можете быстро определить, к какому атрибуту вы пытались получить доступ, и куда перейти, чтобы это исправить.
Большую часть времени, получение этой ошибки определяет, что вы возможно работаете с объектом, тип которого не является ожидаемым:
|
>>> a_list = (1, 2) >>> a_list.append(3) Traceback (most recent call last): File «<stdin>», line 1, in <module> AttributeError: ‘tuple’ object has no attribute ‘append’ |
В примере выше, вы можете ожидать, что a_list будет типом списка, который содержит метод .append(). Когда вы получаете ошибку AttributeError, и видите, что она возникла при попытке вызова .append(), это говорит о том, что вы, возможно, не работаете с типом объекта, который ожидаете.
Часто это происходит тогда, когда вы ожидаете, что объект вернется из вызова функции или метода и будет принадлежать к определенному типу, но вы получаете тип объекта None. В данном случае, строка уведомления об ошибке будет выглядеть так:
AttributeError: ‘NoneType’ object has no attribute ‘append’
Python Ошибка ImportError: No module named [Решено]
ImportError возникает, когда что-то идет не так с оператором import. Вы получите эту ошибку, или ее подкласс ModuleNotFoundError, если модуль, который вы хотите импортировать, не может быть найден, или если вы пытаетесь импортировать что-то, чего не существует во взятом модуле. Документация Python определяет, когда возникает эта ошибка:
Ошибка появляется, когда в операторе импорта возникают проблемы при попытке загрузить модуль. Также вызывается, при конструкции импорта
from listвfrom ... importимеет имя, которое невозможно найти.
Вот пример появления ImportError и ModuleNotFoundError:
|
>>> import asdf Traceback (most recent call last): File «<stdin>», line 1, in <module> ModuleNotFoundError: No module named ‘asdf’ >>> from collections import asdf Traceback (most recent call last): File «<stdin>», line 1, in <module> ImportError: cannot import name ‘asdf’ |
В примере выше, вы можете видеть, что попытка импорта модуля asdf, который не существует, приводит к ModuleNotFoundError. При попытке импорта того, что не существует (в нашем случае — asdf) из модуля, который существует (в нашем случае — collections), приводит к ImportError. Строки сообщения об ошибке трассировок указывают на то, какая вещь не может быть импортирована, в обоих случаях это asdf.
Ошибка IndexError: list index out of range [Решено]
IndexError возникает тогда, когда вы пытаетесь вернуть индекс из последовательности, такой как список или кортеж, и при этом индекс не может быть найден в последовательности. Документация Python определяет, где эта ошибка появляется:
Возникает, когда индекс последовательности находится вне диапазона.
Вот пример, который приводит к IndexError:
|
>>> a_list = [‘a’, ‘b’] >>> a_list[3] Traceback (most recent call last): File «<stdin>», line 1, in <module> IndexError: list index out of range |
Строка сообщения об ошибке для IndexError не дает вам полную информацию. Вы можете видеть, что у вас есть отсылка к последовательности, которая не доступна и то, какой тип последовательности рассматривается, в данном случае это список.
Иными словами, в списке a_list нет значения с ключом
3. Есть только значение с ключами0и1, этоaиbсоответственно.
Эта информация, в сочетании с остальной трассировкой, обычно является исчерпывающей для помощи программисту в быстром решении проблемы.
Возникает ошибка KeyError в Python 3 [Решено]
Как и в случае с IndexError, KeyError возникает, когда вы пытаетесь получить доступ к ключу, который отсутствует в отображении, как правило, это dict. Вы можете рассматривать его как IndexError, но для словарей. Из документации:
Возникает, когда ключ словаря не найден в наборе существующих ключей.
Вот пример появления ошибки KeyError:
|
>>> a_dict = [‘a’: 1, ‘w’: ‘2’] >>> a_dict[‘b’] Traceback (most recent call last): File «<stdin>», line 1, in <module> KeyError: ‘b’ |
Строка уведомления об ошибки KeyError говорит о ключе, который не может быть найден. Этого не то чтобы достаточно, но, если взять остальную часть трассировки, то у вас будет достаточно информации для решения проблемы.
Ошибка NameError: name is not defined в Python [Решено]
NameError возникает, когда вы ссылаетесь на название переменной, модуля, класса, функции, и прочего, которое не определено в вашем коде.
Документация Python дает понять, когда возникает эта ошибка NameError:
Возникает, когда локальное или глобальное название не было найдено.
В коде ниже, greet() берет параметр person. Но в самой функции, этот параметр был назван с ошибкой, persn:
|
>>> def greet(person): ... print(f‘Hello, {persn}’) >>> greet(‘World’) Traceback (most recent call last): File «<stdin>», line 1, in <module> File «<stdin>», line 2, in greet NameError: name ‘persn’ is not defined |
Строка уведомления об ошибке трассировки NameError указывает вам на название, которое мы ищем. В примере выше, это названная с ошибкой переменная или параметр функции, которые были ей переданы.
NameError также возникнет, если берется параметр, который мы назвали неправильно:
|
>>> def greet(persn): ... print(f‘Hello, {person}’) >>> greet(‘World’) Traceback (most recent call last): File «<stdin>», line 1, in <module> File «<stdin>», line 2, in greet NameError: name ‘person’ is not defined |
Здесь все выглядит так, будто вы сделали все правильно. Последняя строка, которая была выполнена, и на которую ссылается трассировка выглядит хорошо.
Если вы окажетесь в такой ситуации, то стоит пройтись по коду и найти, где переменная person была использована и определена. Так вы быстро увидите, что название параметра введено с ошибкой.
Ошибка SyntaxError: invalid syntax в Python [Решено]
Возникает, когда синтаксический анализатор обнаруживает синтаксическую ошибку.
Ниже, проблема заключается в отсутствии двоеточия, которое должно находиться в конце строки определения функции. В REPL Python, эта ошибка синтаксиса возникает сразу после нажатия Enter:
|
>>> def greet(person) File «<stdin>», line 1 def greet(person) ^ SyntaxError: invalid syntax |
Строка уведомления об ошибке SyntaxError говорит вам только, что есть проблема с синтаксисом вашего кода. Просмотр строк выше укажет вам на строку с проблемой. Каретка ^ обычно указывает на проблемное место. В нашем случае, это отсутствие двоеточия в операторе def нашей функции.
Стоит отметить, что в случае с трассировками SyntaxError, привычная первая строка Tracebak (самый последний вызов) отсутствует. Это происходит из-за того, что SyntaxError возникает, когда Python пытается парсить ваш код, но строки фактически не выполняются.
Ошибка TypeError в Python 3 [Решено]
TypeError возникает, когда ваш код пытается сделать что-либо с объектом, который не может этого выполнить, например, попытка добавить строку в целое число, или вызвать len() для объекта, в котором не определена длина.
Ошибка возникает, когда операция или функция применяется к объекту неподходящего типа.
Рассмотрим несколько примеров того, когда возникает TypeError:
|
>>> 1 + ‘1’ Traceback (most recent call last): File «<stdin>», line 1, in <module> TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ >>> ‘1’ + 1 Traceback (most recent call last): File «<stdin>», line 1, in <module> TypeError: must be str, not int >>> len(1) Traceback (most recent call last): File «<stdin>», line 1, in <module> TypeError: object of type ‘int’ has no len() |
Указанные выше примеры возникновения TypeError приводят к строке уведомления об ошибке с разными сообщениями. Каждое из них весьма точно информирует вас о том, что пошло не так.
В первых двух примерах мы пытаемся внести строки и целые числа вместе. Однако, они немного отличаются:
- В первом примере мы пытаемся добавить
strкint. - Во втором примере мы пытаемся добавить
intкstr.
Уведомления об ошибке указывают на эти различия.
Последний пример пытается вызвать len() для int. Сообщение об ошибке говорит нам, что мы не можем сделать это с int.
Возникла ошибка ValueError в Python 3 [Решено]
ValueError возникает тогда, когда значение объекта не является корректным. Мы можем рассматривать это как IndexError, которая возникает из-за того, что значение индекса находится вне рамок последовательности, только ValueError является более обобщенным случаем.
Возникает, когда операция или функция получает аргумент, который имеет правильный тип, но неправильное значение, и ситуация не описывается более детальной ошибкой, такой как IndexError.
Вот два примера возникновения ошибки ValueError:
|
>>> a, b, c = [1, 2] Traceback (most recent call last): File «<stdin>», line 1, in <module> ValueError: not enough values to unpack (expected 3, got 2) >>> a, b = [1, 2, 3] Traceback (most recent call last): File «<stdin>», line 1, in <module> ValueError: too many values to unpack (expected 2) |
Строка уведомления об ошибке ValueError в данных примерах говорит нам в точности, в чем заключается проблема со значениями:
- В первом примере, мы пытаемся распаковать слишком много значений. Строка уведомления об ошибке даже говорит нам, где именно ожидается распаковка трех значений, но получаются только два.
- Во втором примере, проблема в том, что мы получаем слишком много значений, при этом получаем недостаточно значений для распаковки.
Логирование ошибок из Traceback в Python 3
Получение ошибки, и ее итоговой трассировки указывает на то, что вам нужно предпринять для решения проблемы. Обычно, отладка кода — это первый шаг, но иногда проблема заключается в неожиданном, или некорректном вводе. Хотя важно предусматривать такие ситуации, иногда есть смысл скрывать или игнорировать ошибку путем логирования traceback.
Рассмотрим жизненный пример кода, в котором нужно заглушить трассировки Python. В этом примере используется библиотека requests.
Файл urlcaller.py:
|
import sys import requests response = requests.get(sys.argv[1]) print(response.status_code, response.content) |
Этот код работает исправно. Когда вы запускаете этот скрипт, задавая ему URL в качестве аргумента командной строки, он откроет данный URL, и затем выведет HTTP статус кода и содержимое страницы (content) из response. Это работает даже в случае, если ответом является статус ошибки HTTP:
|
$ python urlcaller.py https://httpbin.org/status/200 200 b» $ python urlcaller.py https://httpbin.org/status/500 500 b» |
Однако, иногда данный URL не существует (ошибка 404 — страница не найдена), или сервер не работает. В таких случаях, этот скрипт приводит к ошибке ConnectionError и выводит трассировку:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$ python urlcaller.py http://thisurlprobablydoesntexist.com ... During handling of the above exception, another exception occurred: Traceback (most recent call last): File «urlcaller.py», line 5, in <module> response = requests.get(sys.argv[1]) File «/path/to/requests/api.py», line 75, in get return request(‘get’, url, params=params, **kwargs) File «/path/to/requests/api.py», line 60, in request return session.request(method=method, url=url, **kwargs) File «/path/to/requests/sessions.py», line 533, in request resp = self.send(prep, **send_kwargs) File «/path/to/requests/sessions.py», line 646, in send r = adapter.send(request, **kwargs) File «/path/to/requests/adapters.py», line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,)) |
Трассировка Python в данном случае может быть очень длинной, и включать в себя множество других ошибок, которые в итоге приводят к ошибке ConnectionError. Если вы перейдете к трассировке последних ошибок, вы заметите, что все проблемы в коде начались на пятой строке файла urlcaller.py.
Если вы обернёте неправильную строку в блоке try и except, вы сможете найти нужную ошибку, которая позволит вашему скрипту работать с большим числом вводов:
Файл urlcaller.py:
|
try: response = requests.get(sys.argv[1]) except requests.exceptions.ConnectionError: print(—1, ‘Connection Error’) else: print(response.status_code, response.content) |
Код выше использует предложение else с блоком except.
Теперь, когда вы запускаете скрипт на URL, который приводит к ошибке ConnectionError, вы получите -1 в статусе кода и содержимое ошибки подключения:
|
$ python urlcaller.py http://thisurlprobablydoesntexist.com —1 Connection Error |
Это работает отлично. Однако, в более реалистичных системах, вам не захочется просто игнорировать ошибку и итоговую трассировку, вам скорее понадобиться внести в журнал. Ведение журнала трассировок позволит вам лучше понять, что идет не так в ваших программах.
Обратите внимание: Для более лучшего представления о системе логирования в Python вы можете ознакомиться с данным руководством тут: Логирование в Python
Вы можете вести журнал трассировки в скрипте, импортировав пакет logging, получить logger, вызвать .exception() для этого логгера в куске except блока try и except. Конечный скрипт будет выглядеть примерно так:
|
# urlcaller.py import logging import sys import requests logger = logging.getLogger(__name__) try: response = requests.get(sys.argv[1]) except requests.exceptions.ConnectionError as e: logger.exception() print(—1, ‘Connection Error’) else: print(response.status_code, response.content) |
Теперь, когда вы запускаете скрипт с проблемным URL, он будет выводить исключенные -1 и ConnectionError, но также будет вести журнал трассировки:
|
$ python urlcaller.py http://thisurlprobablydoesntexist.com ... File «/path/to/requests/adapters.py», line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,)) —1 Connection Error |
По умолчанию, Python будет выводить ошибки в стандартный stderr. Выглядит так, будто мы совсем не подавили вывод трассировки. Однако, если вы выполните еще один вызов при перенаправлении stderr, вы увидите, что система ведения журналов работает, и мы можем изучать логи программы без необходимости личного присутствия во время появления ошибок:
|
$ python urlcaller.py http://thisurlprobablydoesntexist.com 2> my—logs.log —1 Connection Error |
Подведем итоги данного обучающего материала
Трассировка Python содержит замечательную информацию, которая может помочь вам понять, что идет не так с вашим кодом Python. Эти трассировки могут выглядеть немного запутанно, но как только вы поймете что к чему, и увидите, что они в себе несут, они могут быть предельно полезными. Изучив несколько трассировок, строку за строкой, вы получите лучшее представление о предоставляемой информации.
Понимание содержимого трассировки Python, когда вы запускаете ваш код может быть ключом к улучшению вашего кода. Это способ, которым Python пытается вам помочь.
Теперь, когда вы знаете как читать трассировку Python, вы можете выиграть от изучения ряда инструментов и техник для диагностики проблемы, о которой вам сообщает трассировка. Модуль traceback может быть полезным, если вам нужно узнать больше из выдачи трассировки.
- Текст является переводом статьи: Understanding the Python Traceback
- Изображение из шапки статьи принадлежит сайту © Real Python
Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.
E-mail: vasile.buldumac@ati.utm.md
Образование
Universitatea Tehnică a Moldovei (utm.md)
- 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
- 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»




