Importing matplotlib causes "int() argument must be a string" error - python

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1

It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.

Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

Related

Why do I get Type Error when trying to plot with matplotlib? [duplicate]

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.
Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

Why is launching JupyterLab from my python2.7 anaconda environment failing with a syntaz error?

First, I'm new to anaconda (3.9) and jupyerlab.
When I launch jupyterlab from my python 3.10.8 environment in the anaconda navigator it works fine
But when I launch it from my python 2.7.18 environment it throws the error below.
EDIT for clarification: I won't be writing code in Py2, but I'm fairly sure I may come across Py2 dependencies at some point so was just setting up an environment for that possibility. Like I said I'm new to anaconda and jupyter - so just exploring for now.
Traceback (most recent call last):
File "/home/bioinfguru/anaconda3/envs/python2718/bin/jupyter-notebook", line 7, in
from notebook.notebookapp import main
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/notebook/__init__.py", line 25, in
from .nbextensions import install_nbextension
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/notebook/nbextensions.py", line 31, in
from .config_manager import BaseJSONConfigManager
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/notebook/config_manager.py", line 15, in
from traitlets.config import LoggingConfigurable
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/traitlets/config/__init__.py", line 6, in
from .application import *
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/traitlets/config/application.py", line 17, in
from decorator import decorator
File "/home/bioinfguru/anaconda3/envs/python2718/lib/python2.7/site-packages/decorator.py", line 162
print('Error in generated code:', file=sys.stderr)
^
SyntaxError: invalid syntax
I tried:
Adding another kernel to jupyterlab but it isn't very intuitive and as I'm new to this I'm not sure I won't be messing up my jupyterlab.
Parsing the error I noticed all calls print the format "line X, in
from Y File". The last call only prints "line X". Not sure what to do with that.
When opening the environment in the terminal it confirms Im using python2.7.18
bioinfguru#bioinfguru-Legion-5-15IAH7H:~$ python -V
Python 2.7.18 :: Anaconda, Inc.
Thanks #MattDMo
"It looks like the current version of decorator only supports Python 3.5+. Not sure when Py2 support was dropped, but it was likely a while ago."
I see how you got there. Next time I'll check the project docs for supported languages

I cannot import libraries into python despite repeatedly installing them

I am struggling to install and import python libraries into my programs. originally I was using pydev but I kept getting messages like:
Traceback (most recent call last): File "C:\Users\satur\eclipse-workspace\DMD experimental\Main.py", line 11, in <module> from matplotlib import pyplot as plot ModuleNotFoundError: No module named 'matplotlib'
I installed matplotlib using py -m pip install matplotlib which produced a few messages like this.
WARNING: The script f2py.exe is installed in 'C:\Users\satur\AppData\Local\Programs\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The scripts fonttools.exe, pyftmerge.exe, pyftsubset.exe and ttx.exe are installed in 'C:\Users\satur\AppData \Local\Programs\Python\Python310\Scripts' which is not on PATH.
I was unsure what this meant so I tried running my program again and got the module not found error again.
being unable to resolve the issue I moved over to spyder because it came with many of the libraries I wanted thus avoiding the issue. however, as soon as I tried to import and install libraries not included with spyder I encountered the module not found error and a similar warning about the path. I added the paths mentioned in the warning to the PATH in spyder now when I run my code get this error message:
runfile('C:/Users/satur/.spyder-py3/proper orthogonal decomposition/dynamic mode decomposition experimental driver.py', wdir='C:/Users/satur/.spyder-py3/proper orthogonal decomposition')
Traceback (most recent call last):
File "C:\Users\satur\AppData\Local\Programs\Spyder\pkgs\spyder_kernels\py3compat.py", line 356, in compat_exec
exec(code, globals, locals)
File "c:\users\satur\.spyder-py3\proper orthogonal decomposition\dynamic mode decomposition experimental driver.py", line 13, in <module>
import mat73
File "C:\Users\satur\AppData\Local\Programs\Python\Python310\Lib\site-packages\mat73\__init__.py", line 11, in <module>
import h5py
File "C:\Users\satur\AppData\Local\Programs\Python\Python310\Lib\site-packages\h5py\__init__.py", line 25, in <module>
from . import _errors
ImportError: cannot import name '_errors' from partially initialized module 'h5py' (most likely due to a circular import) (C:\Users\satur\AppData\Local\Programs\Python\Python310\Lib\site-packages\h5py\__init__.py)
I did some looking around and found this
https://github.com/spyder-ide/spyder/wiki/Working-with-packages-and-environments-in-Spyder#installing-packages-into-the-same-environment-as-spyder
I followed what instructions I understood
import sys; sys.executable
Out[50]: 'C:\\Users\\satur\\AppData\\Local\\Programs\\Spyder\\Python\\python.exe'
which is different from what I get when I run it in command prompt or in the pydev terminal both of which give me
C:\Users\satur\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe
when i go to C:\Users\satur\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\ I see: 3 versions of idel, 3 versions of pip, and 6 versions of python.
I am deeply confused. I want to install and import libraries into my python programs. I want to be able to run my programs in either (or for that matter any) ide. I seem to be hitting the very similar issues in both. every tutorial I have found online describes the steps to take to do this but not what they are or why I am doing them none of them seem to work and the more times I try to install things the more confused I get.
could someone please explain: how to install and import libraries into a python program. what python is doing when I install things and try to import them. and why both IDEs have similar but different errors.

Syntax Error When Trying to Open Downloaded Django Application

I am trying to work on a Django application that I downloaded from bitbucket which uses Python2-based code. Previously, Python 3.6 and Django 2.0 was on my system, so I downgraded to Python 2.7 and Django 1.11 to try to get it to work.
When I go to the project directory and type in "python manage.py runserver," I get a syntax error (this is a shortened version of it, hence the dots):
Unhandled exception in thread started by <function wrapper at 0x0000000006A0A358>
Traceback (most recent call last):
File "C:\Users\M\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
.
.
.
File "C:\Users\M\Anaconda3\lib\site-packages\django\contrib\admindocs\urls.py", line 2, in <module>
from django.contrib.admindocs import views
File "C:\Users\M\Anaconda3\lib\site-packages\django\contrib\admindocs\views.py", line 9, in <module>
from django.contrib.admindocs import utils
File "C:\Users\M\Anaconda3\lib\site-packages\django\contrib\admindocs\utils.py", line 12, in <module>
import docutils.core
File "C:\Users\M\Anaconda3\lib\site-packages\docutils\core.py", line 246
print('\n::: Runtime settings:', file=self._stderr)
^
SyntaxError: invalid syntax
If you have a solution to this problem, please let me know.
As said by #emi, you want to use virtualenv. It's a great tool that allows you to create an isolated virtual environment for each Python project. Each virtual environment can have its own version of every dependency.
On Windows, I recommend using it alongside virtualenvwrapper, witch is is just a very thin wrapper with some higher level commands.
It seems your Python installation is broken so uninstall every version of Python you have, reinstall Python 2 and follow along creating a virtualenv for your project (and for every new one you start). If you need you can install Python 3 in the future as well without messing with you previous envs.

Python 3 + pyQt5 + cx_freeze

Past day has basically been a continuous frustration. I'm trying to create my first pyQt5 application and freeze it to OSX app. Here short chronology of my efforts so far:
Noticed that PyQt5 install is only for Python3. Installed Python3 and pyQt via Homebrew.
Developed application. Everything works when launched from PyCharm.
Installed cx_freeze from source to Python3 since Pycharm's pip installer failed in task.
Trying to freeze the application with cx_freeze only to get syntax error. Resolved it with following advice applied to pyQt5: SyntaxError when using cx_freeze on PyQt app
Checked tutorial for cx_freeze: http://www.pythonschool.net/cxfreeze_mac/ and created a setup.py by the example:
application_title = "simple_PyQt4" #what you want to application to be called
main_python_file = "main.py" #the name of the python file you use to run the program
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includes = ["atexit","re"]
setup(
name = application_title,
version = "0.1",
description = "Sample cx_Freeze PyQt4 script",
options = {"build_exe" : {"includes" : includes }},
executables = [Executable(main_python_file, base = base)])
Run the cx_freeze with "bdist_mac" parameter. This time .app file was generated. However, it doesn't launch. Can't see any errors or information anywhere. Just doesn't launch at all when clicked.
At this point I'm getting really tired of all of this so please help. If you can, please help me either:
1. Install PyQt5 to Python2.7 with Homebrew (tried, couldn't figure it out) so that I can use packaking tools compatible with Python2.
2. Get the freezing process to work properly. If possible give detailed explanations, I'm new to these tools.
I'm also interested in hearing how people are supposed to deploy standalone applications with pyQt5 since the process seems anything other than straightforward.
EDIT: I ran the result "main" in folder as suggested by ThomasK. I got following error but have no idea what it means:
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/cx_Freeze-4.3.2-py3.3-macosx-10.9-x86_64.egg/cx_Freeze/initscripts/Console3.py", line 27, in <module>
exec(code, m.__dict__)
File "main.py", line 8, in <module>
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1565, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1512, in _find_and_load_unlocked
_call_with_frames_removed(import_, parent)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 313, in _call_with_frames_removed
return f(*args, **kwds)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1565, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/importlib/_bootstrap.py", line 1529, in _find_and_load_unlocked
raise exc
ImportError: No module named 'ui'
On main.py I have this import on line 8:
from ui.main import Ui_MainWindow
I have all the .ui files and their .py counterparts at folder named "ui" in my project directory.
EDIT: Output of the freezing process: http://pastebin.com/RR9pNGfR
EDIT: And my project schema: http://pastebin.com/HmsdNXEb
I don't know how far the original poster ever got in solving their problem, and the pastebins referenced are long since deleted so there's not a lot of supplementary material, but the latest version of those cx_freeze instructions at pythonschool, updated on 2014-08-27 (after this question), says:
Unfortunately the current version of cx_Freeze on Mac OS X does not play particularly nicely with Python versions that have been installed from Python.org or PyQt if you have installed it previously using our instructions. Therefore, to ensure that cx_Freeze installs successfully you will need to install Python and PyQt using a package manager called MacPorts.
So, that may have been the problem all along. Installing Python3 and PyQt "via Homebrew" sounds like it may have also resulted in a problematic configuration.

Categories