I normally use PyCharm for python coding, but just for the heck of it, I tried to use Visual Studio Code today, and I'm having some problems.
So I followed the steps shown in the "Getting Started with Python in VS Code" page, and I copied this to my new python project:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
x = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x)) # Plot the sine of each x point
plt.show() # Display the plot
just to test if it works well, and for some random reason, whenever I run this code through terminal/cmd in VSCode, I get this:
ImportError: Missing required dependencies ['numpy']
BUT when I use the Debug Mode, it seems to work perfectly fine.
similar thing happened when I tried to run my previous projects through VSCode. So I thought maybe it was just the problem with my environment, so I changed it to the one where I have my tools installed, but nope, I still got the error.
I tried uninstalling then installing again and that didn't work as well.
I Seriously don't know what's happening right now. Why does it work well in Debug Mode but not in terminal/cmd? does anyone know what to do in this situation?
Thanks!
...In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)
Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
x = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x)) # Plot the sine of each x point
plt.show() # Display the plot
Tip: if you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.
Next, try running the file in the debugger using the "Python: Current file" configuration as described in the last section. (If you still have "stopOnEntry": true in that configuration, you need to select the run command again to continue.)
Unless you're using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, "ModuleNotFoundError: No module named 'matplotlib'". Such a message indicates that the required package isn't available in your system.
To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and run Terminal: Create New Integrated Terminal from the Command Palette (⌃⇧(Windows, Linux Ctrl+Shift+))). This command opens a command prompt for your selected interpreter. Then enter the following commands as appropriate for your operating system (commands may require elevation if the Python interpreter is installed in a protected area of the file system):
Note: If you are unable to install the package or encounter other problems, please file an issue on GitHub so we can help you investigate.
# Don't use with Anaconda distributions because they include matplotlib already.
# macOS
sudo python3 -m pip install matplotlib
# Windows (may require elevation)
py -3 -m pip install matplotlib
# Linux (Debian)
sudo apt-get install python3-tk
python -m pip install matplotlib
from: https://code.visualstudio.com/docs/python/python-tutorial
Got this error and was able to fix it by running conda init in the Python Debug Console terminal, and then closing the terminal before starting a new debug session.
In VS Code undee Windows open Terminal -> New Terminal and run
pip3 install pandas
and then
pip3 install matplotlib
While installing pandas, numpy will be installed as well
I believe it may have something to do with the PATH variables. I just had the same problem in Windows 10 and found out that if I launch VS Code through an anaconda prompt it works just fine, no need to mess around with the PATH variables.
So, instead of opening VS Code through the start menu, just open an anaconda prompt (or anaconda shell), cd to your directory and type code .. That solved my issue.
Related
I have installed Python 3.10.6 and Pycharm community edition.
Everything was working until I tried to use numpy.
pip3 install numpy
import numpy as np
This is the error message:
pip3 install numpy
^^^^^^^
SyntaxError: invalid syntax
I also have tried to use pip install numpy and pip2 install numpy and pip3 install numpy scipy, but same error. Reinstalling both python and pycharm didn't help.
Ah, I understand your problem more specifically now. I also use PyCharm, and this same problem happened to me. It was very frustrating, and took me lots of reading to fix it.
PyCharm and other IDEs (integrated development environment) have something called 'run configurations' attached to each file you are working on. These run configurations basically specify which directory on the hard drive the file will use to read and execute your commands. The directory will contain the libraries you need to run your code.
They use these configurations to make it easy to quickly choose which directory (and which libraries) you want a certain file to use. You must specify these configurations in PyCharm for your specific file to run using Numpy. The great thing about PyCharm is that you can actually specify libraries you want to use within the IDE itself (and bypass having to specify a computer-native directory).
Here's How
Go to PyCharm Preferences
Expand the arrow that says 'Project: (your project name)'
Click on 'Python Interpreter'
Click the small '+' symbol
Type in 'numpy' to search for the library (package)
Click install package
Now try to run your file and it should be good to go!
Note that you must do this for each package you wish to use when accessing your file, and as you advance your programming knowledge it will be necessary to learn how to specify the directory you want PyCharm to run the Python Interpreter from. Since you are only using one library though, I think this solution should be fine for the time being.
You should install numpy with that command in your bash/zsh shell.
pip3 install numpy
the python script can then import it.
to test, run pip3 install numpy
then,
python to open a python shell.
and then you'll see
>>>
Type import numpy as np and be sure it imports. It should now.
It can be maddeningly confusing when first starting out with python and trying to figure out how to download libraries. Here are a few critical things I wish I understood before starting my Python journey, as well as the answer to your question.
Python is the language, and the files that support its functionality are located on the hard drive.
Libraries (like Numpy) can be thought of almost as interpreters (note that we are not using the computer definition of 'interpreter') and are stored alongside the Python files on the hard drive. They give Python more flexibility in terms of what it is able to do by increasing what commands Python is able to understand.
Once a library is downloaded, it must be imported to your Python script before you start writing library-specific commands. Importing a library tells Python: "Hey, I'm going to be writing some commands that you haven't seen before, but here is the library with the commands and what they want you to do in a way that you understand."
'pip' is Python's installer for these libraries.
Ex) I have a csv file that I want to read. I learn that Pandas has a csv reader function:
pandas.read_csv()
If I were to type this function in a script, Python would have no idea what I meant. But if I were to download Pandas, then import it into my script, Python would understand exactly what I'm saying.
How to Download Numpy
Assuming you are on Windows, open the terminal (command prompt) and run the command:
py -m pip install numpy
If you don't already have it, the terminal should have a few lines run and should end with something like 'numpy installed successfully'.
You can check to see if you have it by running the following command in your terminal:
py -m pip list
This command provides you with a list of all the downloaded libraries. You can check among them to make sure Numpy is downloaded.
Importing Libraries
Once you've downloaded the libraries you need, you need to import them into your script (the Python file where you are writing your code) in order for it to run properly. This is accomplished using the import command. One important thing to note is that you can import libraries and assign them a nickname using the as modifier.
Ex) Back to that csv file I want to read. I don't want to type 'pandas' in front of all the Pandas commands, so when I import it into the script I abbreviate it as 'pd':
import pandas as pd
pd.read_csv()
See the difference?
TL;DR for Your Scenario
Go to the terminal, and use the py -m pip list command to check if you have Numpy downloaded. If not, run the py -m pip install numpy command. Then go to your script with your actual python code, and import numpy with the import numpy command. Common Python practice is to import numpy as np, FYI.
Hope this clears things up.
It may say that you need to upgrade pip, which is fine, and it should give you a command to run that will upgrade pip to the newest version.
whenever I try to import matplotlib or matplotlib.pyplot in VS Code I get the error in the title:
Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource)
or
Import "matplotlib.pyplot" could not be resolved from source Pylance(reportMissingModuleSource)
The hyperlink of the reportMissingModuleSource sends me to https://github.com/microsoft/pylance-release/blob/main/DIAGNOSTIC_SEVERITY_RULES.md#diagnostic-severity-rules, where it says:
"Diagnostics for imports that have no corresponding source file. This happens when a type stub is found, but the module source file was not found, indicating that the code may fail at runtime when using this execution environment. Type checking will be done using the type stub."
However, from the explanation I don't understand exactly what's wrong and what I should do to fix this, can someone help me with this?
I can reproduce your question when I select a python interpreter where doesn't exist matplotlib:
So, the solution is opening an integrated Terminal then run pip install matplotlib. After it's installed successfully, please reload window, then the warning should go away.
Just changes the interpreter to 2.7.x in left-bottom corner enter image description here
I experienced a similar issue even after installing vs_BuildTools.
Matplotlib could not be resolved from source parlance
What to do:
open the Command Palette (Ctrl+Shift+P)
Type: Python: Select interpreter Here is the interpreter that worked for me!
Navigate to your project.
Select the latest interpreter or check what interpreter
I had the same issue. Sometimes it's back to multiple versions of python on your device. You just need to change the path. Make sure the correct Python interpreter is selected in your IDE.
In vscode Press CTRL + Shift + P or (⌘ + Shift + P on macOS) to open the command palette. Then type Python select interpreter in the search field and choose the right version.
I have the same issue - I did two things and its working now
Check if there is some earlier versions of python installed on your machine - if yes then remove and reinstall the latest one
Second install the Microsoft C++ Build Tools
https://visualstudio.microsoft.com/visual-cpp-build-tools/
Restart the app and run again.
I was getting the same problem and realised the package install path for my active virtual env wasn't listed in sys.path
after appending this location to sys.path my .ipynb was able to import matplotlib
I know this question is asked a lot, I searched for the last three hours for an answer, but couldn't solve my problem.
As soon as I try to:
import matplotlib.pyplot as plt
my Visual Studio Code IDE tells me that: Unable to import 'matplotlib.pyplot'
My current version of Python is:
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
as you can see, I used the Anaconda package, hence matplotlib should be included. I am Using Mac OS 10.15.2
If I enter
import matplotlib.pyplot as plt
it does import that, however, as soon as I try a basic example, like
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
I obtain:
[<matplotlib.lines.Line2D object at 0x10c23d950>]
And a blank token in my Dashboard pops up, which I can only force to quit.
In the course of trying to solve this problem, I tried anything I saw that was related to this topic, although I did not understand everything of it. I hope I did not make a real damage.
My last step was completely deinstalling anaconda and reinstalling.
Thanks for taking your time!
The module can be imported, but your IDE says module not found, means your linter (vscode uses pylinter) is not configured correctly.
Start PyLint from correct anaconda environment in Visual Studio Code
First you need to install package matplotlib using conda console in your project
conda install -c conda-forge matplotlib
You also can install package using PIP
python -m pip install -U matplotlib
And Finally import your package in your source code
import matplotlib.pyplot as plt
Or another Way you can import
from matplotlib import pyplot as plt
Having come here with this error myself, especially if you're using VS Code you need to make sure that the version of Python you're running in VS Code is the same one that's running on your OS. Otherwise, you can conda install or pip3 install all you want into the OS, but VS Code and Jupyter Notebooks won't know anything about those modules. There are a few ways to figure this out, but mostly it's making sure that the Python version you see when typing python --version in the terminal matches the interpreter shown in the top-right corner of your VS Code window.
When searching about this issue, I came across some questions asking the opposite, i.e., package opens in iPython but not in Jupyter Notebook. But in my case, its the opposite. That's why I posted this question.
I added path\to\anaconda3 and path\to\anaconda3\Lib\site-packages in the environment variable, but it doesn't solve the issue.
I can see the packages in the site-packages folder:
But I just can't import some of the packages in iPython:
or with python in the anaconda cmd:
But it works fine in Jupyter Notebook:
What do/can I do to fix this?
Here's some more info if it helps:
(base) C:\Users\h473>where python
C:\Users\h473\AppData\Local\Continuum\anaconda3\python.exe
(base) C:\Users\h473>where conda
C:\Users\h473\AppData\Local\Continuum\anaconda3\Library\bin\conda.bat
C:\Users\h473\AppData\Local\Continuum\anaconda3\Scripts\conda.exe
(base) C:\Users\h473>where pip
C:\Users\h473\AppData\Local\Continuum\anaconda3\Scripts\pip.exe
P.S.: It doesn't happen for all packages, only some packages, as shown for pandas, numpy and matplotlib in the screenshot below.
When you are using matplotlib (and seaborn is built on top of it) it needs to use a so called backend that is used to display the actual GUI with the plot in it once you execute for example matplotlib.pyplot.show().
When you are running a Jupyter Notebook with matplotlib in inline mode (default I think, but not sure), then a Jupyter specific backend is used (module://ipykernel.pylab.backend_inline). That makes sense, since the plots should not appear in separate windows, but be displayed inside the notebook itself.
When you are in an interactive python or iPython session however, Qt5 was used as
import matplotlib
print(matplotlib.rcParams["backend"]) # this prints the backend that would be loaded when trying anything with pyplot
has revealed. Since you get the error youa re getting, it looks like your QT5 installation is broken. You can try to reinstall them using the conda commands, but for now you could also fall back to using a different backend, that you need to specify before trying to load seaborn:
import matplotlib
matplotlib.use("TkAgg") #use backend TkAgg
import seaborn
You can also change the default backend being loaded to TkAgg by creating a matplotlibrc file in C:\Users\<your name>\.matplotlib\ with
backend : TkAgg
in it.
Brand new to Python (typically program in MSDN C#) and I'm trying to make use of the matplotlib to generate some graphics from .csv files
I've downloaded & installed Python as well as Anaconda onto my Windows 10 machine, the versions are Python 3.5.2 and Anaconda 4.1.1
I open up the Python "notepad" interface and do
import matplotlib.pyplot as plt
plt.plot([1,2,3],[3,2,1])
plt.show()
but when I run the code I get the error:
ImportError: No module named 'matplotlib'
I've looked at some other posts for this but they all seem to be in regard to Mac OSX or Linux. Some have pointed to multiple installs of matplotlib, but I haven't turned up such a situation so far. What might be causing this, or how can I troubleshoot it?
**Edit:
The path returned to me from the import sys recommended in the comments gave me this response
['C:\Users\a.watts.ISAM-NA\Desktop',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\python35.zip',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\DLLs',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\lib',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\lib\site-packages',
'C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\lib\site-packages\setuptools-26.1.1-py3.5.egg']
You essentially have 2 versions of python on your system - the standard one you downloaded and the one that ships with Anaconda. When you are running code in the IDLE you are using the standard version (in C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\python.exe) where matplotlib isn't installed which is why you are getting the error.
You need to use the Anaconda version (C:\Users\a.watts.ISAM-NA\AppData\Local\continuum\anaconda3\python.exe) that comes with the scientific stuff already setup. It looks like your system is using this one from the cmd so if you run scripts from there it should use the Anaconda version. If you want to use something more interactive you can also use spyder - the Anaconda version of the IDLE - or run jupyter notebook from cmd to get a browser based platform for interactive development