PyCharm import matplotlib.pyplot show error - python

import numpy as np
import matplotlib.pyplot as plt
def main():
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
if __name__ == '__main__':
main()
Traceback (most recent call last):
File
"/Users/tim/workspace/Python/MachineLearn/test.py", line 2, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
[backend_name], 0)
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 11, in <module>
from datalore.display import display
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/__init__.py", line 1, in <module>
from .display_ import *
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/display_.py", line 5, in <module>
from urllib.parse import urlencode
ImportError: No module named parse
Process finished with exit code 1
=================
Python: 2.7.16
PyCharm Professional: 2019.2
=================
btw, the code run in console mode is work

Simple answer: disable "show plots in scientific window" (Settings -> Tools -> Python Scientific) or downgrade the PyCharm or move your project to python3
Remember to add plt.show() in your code.
A little more complicated. You need to write own importing hooks to find that urllib.parse and urllib.request (next line in display_.py file are requested. More you can read here https://xion.org.pl/2012/05/06/hacking-python-imports/
(i'm not enough familiar with python 2 import system to write it)

For python 2 use
from urlparse import urlparse
If you need to write code which is Python2 and Python3 compatible you can use the following import
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
In your PyCharm project:
press Ctrl+Alt+s to open the settings
on the left column, select Project Interpreter
on the top right there is a list of python binaries found on your system, pick the right one
eventually click the + button to install additional python modules, in your case, it is parse module is missing so install that one

As mentioned by #Grzegorz Bokota, the problem is coming from the "scientific view mode" of PyCharm. This mode allows to visualise graphs and is thus calling matplotlib, and probably an incompatible version of it if you are using Python 2. This bug has been identified here and it seems that we just have to wait for the next release to get it solved.

Related

ImportError when using trackviz module

I'm assigned to run a python script, that imports several module
#filename: animate_vid_v6.py
import numpy as np
import pandas as pd
import imageio
from trackviz import animate
import sys
from matplotlib.patches import Circle
from operator import itemgetter
import colorsys
after I installed all the required modules, I get this error message.
Traceback (most recent call last):
File "<some_directories>\animate_vid_v6.py", line 4, in <mo
dule>
from trackviz import animate
File "C:\Python39\lib\site-packages\trackviz\animate.py", line 9, in <module>
from trackviz.tools import FigureAxes
File "C:\Python39\lib\site-packages\trackviz\tools.py", line 3, in <module>
from mpl_toolkits.axes_grid1 import Divider, LocatableAxes, Size
ImportError: cannot import name 'LocatableAxes' from 'mpl_toolkits.axes_grid1' (
C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1\__init__.py)
After I scrutinize that message, it is turn out that the LocatableAxes is no longer exists in scripts inside the C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1 directory.
As you can see here, at the C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1\__init__.py, there are no LocatableAxes module.
from . import axes_size as Size
from .axes_divider import Divider, SubplotDivider, make_axes_locatable
from .axes_grid import Grid, ImageGrid, AxesGrid
from .parasite_axes import host_subplot, host_axes
Does anybody has an idea /suggestions to fix this problem? thanks.
The LocatableAxes classes have been deprecated in Matplotlib 3.0.0, but it seems trackviz hasn't been updated since then to avoid using these classes. Indeed, the trackviz GitHub repository hasn't been updated for about three years.
If you really want to use trackviz you will have to install an older version of Matplotlib.

python: from x import isn't work in directory

my files are look like this
-root/
-main.py
-nyaizhel_includes/
-includemain.py
-commands/
-astolfo.py
-naruto.py
...
from main.py, i import includemain.py
from nyaizhel_includes import includemain
it works, includemain.py gets imported,
from includemain.py i import commands
from commands import astolfo
from commands import narutobanner
from commands import rgirl
...
includemain.py gets included but astolfo isn't get included, why?
console log
heroku[main.1]: State changed from starting to up
2021-04-13T09:42:02.840988+00:00 app[main.1]: Traceback (most recent call last):
2021-04-13T09:42:02.841010+00:00 app[main.1]: File "/app/main.py", line 42, in <module>
2021-04-13T09:42:02.841140+00:00 app[main.1]: from nyaizhel_includes import includemain
2021-04-13T09:42:02.841141+00:00 app[main.1]: File "/app/nyaizhel_includes/includemain.py", line 1, in <module>
2021-04-13T09:42:02.841258+00:00 app[main.1]: from commands import astolfo
2021-04-13T09:42:02.841262+00:00 app[main.1]: ModuleNotFoundError: No module named 'commands'
2021-04-13T09:42:02.950174+00:00 heroku[main.1]: Process exited with status 1
2021-04-13T09:42:03.023470+00:00 heroku[main.1]: State changed from up to crashed
You didn't list your __init__.py file in your example, so make sure you add those so these are recognized as standard packages (although it seems you may already have).
The source of your error is likely that you're trying to do a relative import but specifying an absolute import:
If you use from .commands import astolfo (notice the period to signify relative import), that should resolve your issue. It is recommended to use absolute imports as per the PEP 8 Style guide however. In your case this would be from nyaizhel_includes.commands import astolfo, assuming nyaizhel_includes is your root package here.
See the documentation on Python packages for more information.

Import errors on VS code

I'm new to VS code. I have downloaded a git project which has demo programs that I can run.
The directory structure is as follows:
Projectparser
>demo
>>alg1_demo.py
>>alg2_demo.py
>>alg3_demo.py
>Projectparser
>>alg1
>>>__init__ [ Has just one line : from alg1 import * ]
>>>alg1.py
>>>calg1.c
>>>calg1.h
>>alg2
>>>__init__ [ Has just one line : from alg2 import * ]
>>>alg2.py
>>>calg2.c
>>>calg2.h
>>alg3
>>>__init__ [ Has just one line : from alg3 import * ]
>>>alg3.py
>>>calg3.c
>>>calg3.h
where > indicates sub-directory. Projectparser is the folder from where I open vs code. It has a sub-directory by the same name as well which contains all the algorithms I'm interested in.
When I try running the alg1_demo.py. The below line is causing an error.
sys.append("../")
from Projectparser import alg1 (line 8)
I'm getting the following error:
ImportError: cannot import name 'alg1' from 'Projectparser' (unknown location)
So I added the line : sys.path.append("../Projectparser")
Then I'm getting the following error :
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
ModuleNotFoundError: No module named 'alg1'
But the module is present in the subdirectory. So I added the line :
sys.path.append("../Projectparser/Projectparser/alg1")
Then I'm getting this error :
Traceback (most recent call last):
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
File "/home//Projectparser/Projectparser/alg1/alg1.py", line 13, in <module>
from ..logmatch import regexmatch
ImportError: attempted relative import with no known parent package
The same problem persists for all the three algorithms alg1, alg2, alg3. I'm not sure how to fix this and is using sys.append.path() the best way to solve the above mentioned problems.
Can anyone suggest how to solve the final import error : ImportError: attempted relative import with no known parent package
and if there is any other compact way of solving the other import errors instead of using sys.path.append().
Thanks in advance
Use the following statement to add the path of the file that needs to be imported to the system path to help VSCode find it:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
The following is part of the project I created that you provided:
Result:
The following points need to be noted:
When importing, the subfolders are connected with.
Please avoid using files and folders with the same name to prevent confusion when VSCode finds modules.
If the result is executable but there is still a wave line, you can add in settings.json: "python.linting.pylintArgs": [ "----extension-pkg-whitelist=1xml" ],
Update:
According to the code of the link you provided, I reproduced the problem you described locally, and the solution is as follows:
Comment out the content "from SLCT import *" of logparser-master\logparser\SLCT_init_.py.
Add import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
to SLCT_demo.py
operation result:

ImportError: cannot import module

The package looks like this:
main.py
HTTPQuery.py
SmartDownload.py
in main.py I run from SmartDownload import DownloadFile.
in Smartdownload.py I run from HTTPQuery import Is_ServerSupportHTTPRange
in HTTPQuery I run from SmartDownload import DownloadFile
It seems that I get stuck in a loop, because this is the error:
Traceback (most recent call last):
File "C:\Scripts\mp3grabber\main.py", line 13, in <module>
import HTTPQuery
File "C:\Scripts\mp3grabber\HTTPQuery.py", line 6, in <module>
from SmartDownload import DownloadFile
File "C:\Scripts\mp3grabber\SmartDownload.py", line 3, in <module>
from HTTPQuery import Is_ServerSupportHTTPRange
ImportError: cannot import name Is_ServerSupportHTTPRange
But I must import second file's functions into the third file and vice-versa.
What can I do?
As you suggest, there is a circular dependency between HTTPQuery and SmartDownload. The easy fix is to move the import into the functions that require it, e.g.
# SmartDownload.py
def download(url):
from HTTPQuery import Is_ServerSupportHTTPRange
...
A better solution might be to reorganize your modules. If there is no reasonable way to remove HTTPQuery's dependence on SmartDownload or vice versa, consider merging them into one module.
Your best option is to re-organize the dependencies so you don't have this circular import problem. Barring that, you may be able to simply move the line from SmartDownload import DownloadFile to the bottom of your HTTPQuery.py file to break the loop.
There's a bit of discussion on circular imports here.

Python Wildcard Import Vs Named Import

Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this:
MainApp.py
res/
__init__.py
elements/
__init__.py
MainFrame.py
Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame.
In MainApp.py this works:
from res.elements.MainFrame import *
And this does not:
from res.elements.MainFrame import RPMWindow
I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds.
When using the class name I get this traceback:
Traceback (most recent call last):
File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 953, in <module>
debugger.run(setup['file'], None, None)
File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 780, in run
execfile(file, globals, locals) #execute the script
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
from res.elements.MainFrame import RPMWindow
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module>
from res.elements.MenuBar import MenuBarBuilder
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module>
from MainApp import _, DataCache
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
from res.elements.MainFrame import RPMWindow
ImportError: cannot import name RPMWindow
When using the wild card import I don't receive a traceback and my application opens.
You have circular imports:
MainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError.
i don't have time to look into why the wildcard is working for you, but what i can say about your failure with the direct name import is that you have an import cycle in your code:
you are trying to import res.elements.MainFrame, but part of that code is trying to import res.elements.MenuBar which tries to import res.elements.MainFrame again. IOW, your first attempt to import res.elements.MainFrame has not completed yet before you try it again.
You have circular imports in your code: the same module is both required by and requires the use of a certain other module, which when you think of it like that, it clearly precarious. Most of the problems can be cleared up by using import a and later referring to a.b instead of from a import b or from a import *.
In particular, never use from a import *. Wildcard imports clutter your namespace and makes your code less maintainable, readable, sane, and predictable. The difference between import a and from a import * is the difference between dragging a box into a room and pouring its contents all over the floor.
It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.

Categories

Resources