No module named ‘numpy’: Visual Studio Code
Also, is there python interactive window in VS Code? How to open it.
219k 55 55 gold badges 471 471 silver badges 480 480 bronze badges
asked Oct 21, 2016 at 21:04
815 5 5 gold badges 14 14 silver badges 25 25 bronze badges
Do you have mutiple Python installations on your system?
Oct 21, 2016 at 21:14
I don’t see where you said you installed numpy. (Does it come with Anaconda or Visual Studio Code? I’m not familiar with those.)
Oct 21, 2016 at 21:24
Numpy comes with Anaconda, I have Anaconda 2.7 and 3.5 64-bit versions
Oct 21, 2016 at 21:53
see solution stackoverflow.com/questions/29987840/… for using anaconda python environment and python libraries.
Sep 2, 2021 at 21:00
15 Answers 15
Changing python environment in VS code helped me. Default the visual studio code takes original Python environment, it requires numpy to install. If you have anaconda python (numpy comes with it) installed, you could switch the original python environment to anaconda python environment in visuals studio code. This can be done from the command palette Ctrl+Shift+P in visual studio
Check this link for how to switch from original python to anaconda python environment, specifically:

2,179 2 2 gold badges 17 17 silver badges 23 23 bronze badges
answered Mar 4, 2018 at 2:56
Madhukar Reddy Madhukar Reddy
521 1 1 gold badge 4 4 silver badges 2 2 bronze badges
I’m getting the same error even after creating a separate environment via anaconda and then choosing that environment in VS Code
Jan 28 at 17:33
You may not have numpy installed on the version of python you are running.
Is the printed version Anaconda? If you installed Anaconda python, it should come with numpy already installed. If it turns out to be another version of python you are accessing inside Visual Studio Code that doesn’t have numpy installed, then that’s what you need to fix.
The version of python that is called depends on which version of python comes up in your PATH variable first. Type into a terminal: echo $PATH . The output should look like this with Anaconda bin first: /Users/jlzhang/anaconda/bin:/usr/local/bin:/usr/bin:/bin
If you do not have Anaconda bin first, you can add this to your ~/.bashrc file: echo
# Use Anaconda python
export PATH=»/Users/jlzhang/anaconda/bin:$PATH»
Restart a terminal and Visual Studio Code and see if you are now running Anaconda python.
Hope it helps/ Did it work?
How to Install Pandas into Visual Studio Code
In this blog, we’ll demonstrate how to seamlessly integrate the powerful Pandas library into Visual Studio Code, a favored Python IDE among data scientists and software engineers. Elevate your data analysis capabilities and streamline your workflow with this essential tool in your toolkit.
By Saturn Cloud | Monday, June 19, 2023 | Miscellaneous

As a data scientist or software engineer, you know the importance of having the right tools in your toolbox. One of the most popular tools for data analysis in Python is the Pandas library. In this article, we’ll show you how to install Pandas into Visual Studio Code, a popular integrated development environment (IDE) for Python.
What is Pandas?
Before we dive into the installation process, let’s first define what Pandas is and why it’s so useful. Pandas is a Python library that provides data manipulation and analysis tools. It’s built on top of the NumPy library, which provides support for large, multi-dimensional arrays and matrices. Pandas makes it easy to work with data in a variety of formats, including CSV, Excel, SQL databases, and more.
Some of the key features of Pandas include:
- Dataframe and series objects for working with tabular data
- Support for data cleaning, filtering, and transformation
- Built-in support for handling missing or null values
- Integration with other Python libraries, such as Matplotlib and Scikit-learn
Now that you know what Pandas is and what it can do, let’s move on to the installation process.
How to Install Pandas in Visual Studio Code
Installing Pandas in Visual Studio Code is a straightforward process that can be completed in just a few steps. Here’s what you need to do:
Step 1: Install Python
Before you can install Pandas, you need to have Python installed on your computer. If you haven’t already done so, you can download the latest version of Python from the official Python website (https://www.python.org/downloads/). Be sure to download the version that matches your operating system (Windows, macOS, or Linux).
Step 2: Open Visual Studio Code
Once you have Python installed, you can open Visual Studio Code. If you don’t already have it installed, you can download it from the official Visual Studio Code website (https://code.visualstudio.com/download).
Step 3: Open the Terminal
In Visual Studio Code, click on the Terminal tab at the top of the screen. This will open a new terminal window at the bottom of the screen.
Step 4: Install Pandas
In the terminal window, type the following command to install Pandas:
pip install pandas
This will download and install the latest version of Pandas from the Python Package Index (PyPI). Depending on your internet connection speed, this process may take a few minutes. You can also choose the specific version of Pandas that you want to install by typing the following command:
pip install pandas==2.1.1 # this command will install Pandas version 2.1.1 to your computer.
Step 5: Verify the Installation
Once the installation is complete, you can verify that Pandas has been installed correctly by typing the following command in the terminal window:
python -c "import pandas; print(pandas.__version__)"
This will print the version number of Pandas that you just installed, either the latest version or the specific one that you defined. If you see a version number, then Pandas has been installed correctly.
Conclusion
In this article, we’ve shown you how to install Pandas into Visual Studio Code, a popular IDE for Python. Pandas is a powerful library for data manipulation and analysis, and it’s a must-have tool for any data scientist or software engineer working with Python. By following the steps outlined in this article, you can quickly and easily install Pandas and start working with data in Visual Studio Code.
About Saturn Cloud
Saturn Cloud is your all-in-one solution for data science & ML development, deployment, and data pipelines in the cloud. Spin up a notebook with 4TB of RAM, add a GPU, connect to a distributed cluster of workers, and more. Join today and get 150 hours of free compute per month.
maksbotan / readme.md
Наш курс включает в себя решения задач на практических занятиях, а также домашние задания. Для этого вам понадобится ноутбук с Python.
Если у вас уже установлен Python и вы уверены, что умеете им пользоваться, переходите сразу к разделам «Установка нужных библиотек» и «Дополнительные материалы».
Если у вас Mac — попробуйте адаптировать эту инструкцию для себя или обратитесь за помощью к организаторам курса. Если же у вас Linux, то вы скорее всего сами всё знаете. Если что-то всё же не получается, попросите помощи в нашем чате.
Мы будем пользоваться Python 3.8. Скачать его можно по этой ссылке. Запустите скачанный файл для установки.
Рекомендуем на первом экране нажать «Customize installation»:
и на следующем выбрать «Install for all users» и «Add Python to environment variables»:
Теоретически, код на Python можно писать в любом текстовом редакторе, включая Блокнот. Однако решать задачу будет гораздо удобнее если установить специально для этого предназначенный.
Мы рекомендуем пользоваться Visual Studio Code. Скачать можно здесь.
Настройка VS Code
Нам понадобится установить расширение VS Code, включающее поддержку Python. Для этого нажмите нижнюю кнопку в левой панели (состоит из 4 квадратиков), введите в строке поиска «Python», выберите первое расширение (как на картинке ниже) и нажмите зеленую кнопку Install.

Создайте новый файл («File» -> «New File») и сохраните его с расширением .py , например hello.py .
Если всё установлено правильно, в левом нижнем углу вы увидите надпись «Python 3.8.7 64-bit». Это значит, что VS Code «увидел» Python, который вы установили.
Запуск ваших программ
Напишите в этом новом файле такой код:
print("Hello, world!")
Теперь нажмите в любом месте правой кнопкой мыши и выберите пункт «Run Python File in Terminal». Внизу экрана вы увидите окно Terminal, в котором будет напечатана строка » Hello, world! «.
Установка нужных библиотек
В наших заданиях нам понадобятся библиотеки numpy и biopython . Самый простой способ их установить — перейти в окно Terminal в VS Code и набрать там команду
pip3 install --user numpy biopython
Если эта команда не выведет никаких ошибок (красным текстом), значит вы готовы к нашему курсу!
Если вы ещё никогда не писали на Python или просто не уверены в своих знаниях, рекомендуем несколько хороших материалов.
- Самоучитель Python, в котором можно делать упражнения прямо в окна браузера: https://pythontutor.ru
- Небольшая книга-самоучитель по языку: https://pythonworld.ru/samouchitel-python
- И бесплатный видео курс по Python от Института Биоинформатики: https://stepik.org/course/67/promo
Flask Tutorial in Visual Studio Code
Flask is a lightweight Python framework for web applications that provides the basics for URL routing and page rendering.
Flask is called a «micro» framework because it doesn’t directly provide features like form validation, database abstraction, authentication, and so on. Such features are instead provided by special Python packages called Flask extensions. The extensions integrate seamlessly with Flask so that they appear as if they were part of Flask itself. For example, Flask doesn’t provide a page template engine, but installing Flask includes the Jinja templating engine by default. For convenience, we typically speak of these defaults as part of Flask.
In this Flask tutorial, you create a simple Flask app with three pages that use a common base template. Along the way, you experience a number of features of Visual Studio Code including using the terminal, the editor, the debugger, code snippets, and more.
The completed code project for this Flask tutorial can be found on GitHub: python-sample-vscode-flask-tutorial.
If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.
Prerequisites
To successfully complete this Flask tutorial, you must do the following (which are the same steps as in the general Python tutorial):
- Install the Python extension.
- Install a version of Python 3 (for which this tutorial is written). Options include:
- (All operating systems) A download from python.org; typically use the Download button that appears first on the page.
- (Linux) The built-in Python 3 installation works well, but to install other Python packages you must run sudo apt install python3-pip in the terminal.
- (macOS) An installation through Homebrew on macOS using brew install python3 .
- (All operating systems) A download from Anaconda (for data science purposes).
- On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running path at the command prompt. If the Python interpreter’s folder isn’t included, open Windows Settings, search for «environment», select Edit environment variables for your account, then edit the Path variable to include that folder.
Create a project environment for the Flask tutorial
In this section, you will create a virtual environment in which Flask is installed. Using a virtual environment avoids installing Flask into a global Python environment and gives you exact control over the libraries used in an application.
- On your file system, create a folder for this tutorial, such as hello_flask .
- Open this folder in VS Code by navigating to the folder in a terminal and running code . , or by running VS Code and using the File >Open Folder command.
- In VS Code, open the Command Palette (View >Command Palette or ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) )). Then select the Python: Create Environment command to create a virtual environment in your workspace. Select venv and then the Python environment you want to use to create it.
Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

After your virtual environment creation has been completed, run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) )) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
Note: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run activate.ps1 because running scripts is disabled on the system. The error provides a link for information on how to allow scripts. Otherwise, use Terminal: Select Default Profile to set «Command Prompt» or «Git Bash» as your default instead.
python -m pip install flask
You now have a self-contained environment ready for writing Flask code. VS Code activates the environment automatically when you use Terminal: Create New Terminal. If you open a separate command prompt or terminal, activate the environment by running source .venv/bin/activate (Linux/macOS) or .venv\Scripts\Activate.ps1 (Windows). You know the environment is activated when the command prompt shows (.venv) at the beginning.
Create and run a minimal Flask app
![]()
- In VS Code, create a new file in your project folder named app.py using either File >New from the menu, pressing Ctrl+N , or using the new file icon in the Explorer View (shown below).
- In app.py , add code to import Flask and create an instance of the Flask object. If you type the code below (instead of using copy-paste), you can observe VS Code’s IntelliSense and auto-completions:
from flask import Flask app = Flask(__name__)
@app.route("/") def home(): return "Hello, Flask!"
Tip: You can use multiple decorators on the same function, one per line, depending on how many different routes you want to map to the same function.
(.venv) D:\py\\hello_flask>python -m flask run * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

If you see an error that the Flask module cannot be found, make sure you’ve run python -m pip install flask in your virtual environment as described at the end of the previous section. Also, if you want to run the development server on a different IP address or port, use the host and port command-line arguments, as with —host=0.0.0.0 —port=80 .
127.0.0.1 - - [11/Jul/2018 08:40:15] "GET / HTTP/1.1" 200 -
Tip: When using a different filename than app.py , such as webapp.py , you will need to define an environment variable named FLASK_APP and set its value to your chosen file. Flask’s development server then uses the value of FLASK_APP instead of the default file app.py . For more information, see Flask command line interface.
Run the app in the debugger
Debugging gives you the opportunity to pause a running program on a particular line of code. When a program is paused, you can examine variables, run code in the Debug Console panel, and otherwise take advantage of the features described on Debugging. Running the debugger also automatically saves any modified files before the debugging session begins.
Before you begin: Make sure you’ve stopped the running app at the end of the last section by using Ctrl+C in the terminal. If you leave the app running in one terminal, it continues to own the port. As a result, when you run the app in the debugger using the same port, the original running app handles all the requests and you won’t see any activity in the app being debugged and the program won’t stop at breakpoints. In other words, if the debugger doesn’t seem to be working, make sure that no other instance of the app is still running.
-
Replace the contents of app.py with the following code, which adds a second route and function that you can step through in the debugger:
import re from datetime import datetime from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" @app.route("/hello/") def hello_there(name): now = datetime.now() formatted_now = now.strftime("%A, %d %B, %Y at %X") # Filter the name argument to letters only using regular expressions. URL arguments # can contain arbitrary text, so we restrict to safe characters only. match_object = re.match("[a-zA-Z]+", name) if match_object: clean_name = match_object.group(0) else: clean_name = "Friend" content = "Hello there, " + clean_name + "! It's " + formatted_now return content
- With the cursor on that line, press F9 , or,
- With the cursor on that line, select the Run >Toggle Breakpoint menu command, or,
- Click directly in the margin to the left of the line number (a faded red dot appears when hovering there).
The breakpoint appears as a red dot in the left margin:


"name": "Python: Flask", "type": "python", "request": "launch", "module": "flask", "env": "FLASK_APP": "app.py", "FLASK_DEBUG": "1" >, "args": [ "run", "--no-debugger", "--no-reload" ], "jinja": true, "justMyCode": true >,
Note: If the env entry in your configuration contains «FLASK_APP»: «$/app.py» , change it to «FLASK_APP»: «app.py» as shown above. Otherwise you may encounter error messages like «Cannot import module C» where C is the drive letter where your project folder resides.
Note: Once launch.json is created, an Add Configuration button appears in the editor. That button displays a list of additional configurations to add to the beginning of the configuration list. (The Run > Add Configuration menu command does the same action.).

Observe that the status bar changes color to indicate debugging:
A debugging toolbar (shown below) also appears in VS Code containing commands in the following order: Pause (or Continue, F5 ), Step Over ( F10 ), Step Into ( F11 ), Step Out ( ⇧F11 (Windows, Linux Shift+F11 ) ), Restart ( ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 ) ), and Stop ( ⇧F5 (Windows, Linux Shift+F5 ) ). See VS Code debugging for a description of each command. 


now.strftime("%A, %d %B, %Y at %X") 'Wednesday, 31 October, 2018 at 18:13:39'
Tip: The Debug Console also shows exceptions from within the app that may not appear in the terminal. For example, if you see a «Paused on exception» message in the Call Stack area of Run and Debug view, switch to the Debug Console to see the exception message.
now.strftime("%a, %d %B, %Y at %X") 'Wed, 31 October, 2018 at 18:13:39' now.strftime("%a, %d %b, %Y at %X") 'Wed, 31 Oct, 2018 at 18:13:39' now.strftime("%a, %d %b, %y at %X") 'Wed, 31 Oct, 18 at 18:13:39'

Tip: To make it easier to repeatedly navigate to a specific URL like http://127.0.0.1:5000/hello/VSCode , output that URL using a print statement. The URL appears in the terminal where you can use Ctrl+click to open it in a browser.
Go to Definition and Peek Definition commands
During your work with Flask or any other library, you may want to examine the code in those libraries themselves. VS Code provides two convenient commands that navigate directly to the definitions of classes and other objects in any code:

- Go to Definition jumps from your code into the code that defines an object. For example, in app.py , right-click on the Flask class (in the line app = Flask(__name__) ) and select Go to Definition (or use F12 ), which navigates to the class definition in the Flask library.
- Peek Definition ( ⌥F12 (Windows Alt+F12 , Linux Ctrl+Shift+F10 ) , also on the right-click context menu), is similar, but displays the class definition directly in the editor (making space in the editor window to avoid obscuring any code). Press Escape to close the Peek window or use the x in the upper right corner.
Use a template to render a page
The app you’ve created so far in this tutorial generates only plain text web pages from Python code. Although it’s possible to generate HTML directly in code, developers avoid such a practice because it opens the app to cross-site scripting (XSS) attacks. In the hello_there function of this tutorial, for example, one might think to format the output in code with something like content = «
Hello there, » + clean_name + «!
» , where the result in content is given directly to a browser. This opening allows an attacker to place malicious HTML, including JavaScript code, in the URL that ends up in clean_name and thus ends up being run in the browser.
A much better practice is to keep HTML out of your code entirely by using templates, so that your code is concerned only with data values and not with rendering.
- A template is an HTML file that contains placeholders for values that the code provides at run time. The templating engine takes care of making the substitutions when rendering the page. The code, therefore, concerns itself only with data values and the template concerns itself only with markup.
- The default templating engine for Flask is Jinja, which is installed automatically when you install Flask. This engine provides flexible options including automatic escaping (to prevent XSS attacks) and template inheritance. With inheritance, you can define a base page with common markup and then build upon that base with page-specific additions.
In this section, you create a single page using a template. In the sections that follow, you configure the app to serve static files, and then create multiple pages to the app that each contains a nav bar from a base template.
- Inside the hello_flask folder, create a folder named templates , which is where Flask looks for templates by default.
- In the templates folder, create a file named hello_there.html with the contents below. This template contains two placeholders named «name» and «date», which are delineated by pairs of curly braces, > . As you can see, you can also include formatting code in the template directly:
html> charset="utf-8" /> Hello, Flask Hello there, >! It's >. What's your name? Provide it after /hello/ in the URL.
Tip: Flask developers often use the flask-babel extension for date formatting, rather than strftime , as flask-babel takes locales and timezones into consideration.
from flask import render_template
@app.route("/hello/") @app.route("/hello/") def hello_there(name = None): return render_template( "hello_there.html", name=name, date=datetime.now() )
Serve static files
Static files are of two types. First are those files like stylesheets to which a page template can just refer directly. Such files can live in any folder in the app, but are commonly placed within a static folder.
The second type are those that you want to address in code, such as when you want to implement an API endpoint that returns a static file. For this purpose, the Flask object contains a built-in method, send_static_file , which generates a response with a static file contained within the app’s static folder.
The following sections demonstrate both types of static files.
Refer to static files in a template
- In the hello_flask folder, create a folder named static .
- Within the static folder, create a file named site.css with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview:
.message font-weight: 600; color: blue; >
rel="stylesheet" type="text/css" href=">" />
class="message">Hello there, >! It's >. class="message">What's your name? Provide it after /hello/ in the URL.
Serve a static file from code
- In the static folder, create a JSON data file named data.json with the following contents (which are meaningless sample data):
"01": "note": "This data is very simple because we're demonstrating only the mechanism." > >
@app.route("/api/data") def get_data(): return app.send_static_file("data.json")
Create multiple templates that extend a base template
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates can then extend (this is also called template inheritance.)
Also, because you’ll likely create many pages that extend the same template, it’s helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.
The following sections walk through different parts of this process.
Create a base page template and styles
A base page template in Flask contains all the shared parts of a set of pages, including references to CSS files, script files, and so forth. Base templates also define one or more block tags that other templates that extend the base are expected to override. A block tag is delineated by %> and in both the base template and extended templates.
The following steps demonstrate creating a base template.
-
In the templates folder, create a file named layout.html with the contents below, which contains blocks named «title» and «content». As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you will create in a later section. Each link again uses Flask’s url_for tag to generate a link at runtime for the matching route.
html> charset="utf-8" /> rel="stylesheet" type="text/css" href=">" /> class="navbar"> href=">" class="navbar-brand">Home href=">" class="navbar-item">About href=">" class="navbar-item">Contact class="body-content">
© 2018
.navbar background-color: lightslategray; font-size: 1em; font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; color: white; padding: 8px 5px 8px 5px; > .navbar a text-decoration: none; color: inherit; > .navbar-brand font-size: 1.2em; font-weight: 600; > .navbar-item font-variant: small-caps; margin-left: 30px; > .body-content padding: 5px; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; >
You can run the app at this point, but because you haven’t made use of the base template anywhere and haven’t changed any code files, the result is the same as the previous step. Complete the remaining sections to see the final effect.
Create a code snippet
Because the three pages you create in the next section extend layout.html , it saves time to create a code snippet to initialize a new template file with the appropriate reference to the base template. A code snippet provides a consistent piece of code from a single source, which avoids errors that can creep in when using copy-paste from existing code.
- In VS Code, select File >Preferences >Configure User Snippets.
- In the list that appears, select html. The option may appear as «html.json» in the Existing Snippets section of the list if you’ve created snippets previously.
- After VS Code opens html.json , add the following entry within the existing curly braces (the explanatory comments, not shown here, describe details such as how the $0 line indicates where VS Code places the cursor after inserting a snippet):
"Flask Tutorial: template extending layout.html": "prefix": "flextlayout", "body": [ " \"layout.html\" %>", "", "$0", "", "", "" ], "description": "Boilerplate template that extends layout.html" >,
For more information on code snippets in general, refer to Creating snippets.
Use the code snippet to add pages
With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.
- In the templates folder, create a new file named home.html , Then start typing flext to see the snippet appear as a completion:
When you select the completion, the snippet’s code appears with the cursor on the snippet’s insertion point: 
- At the insertion point in the «title» block, write Home , and in the «content» block, write
Home page for the Visual Studio Code Flask tutorial.
, then save the file. These lines are the only unique parts of the extended page template:
- In the templates folder, create about.html , use the snippet to insert the boilerplate markup, insert About us and
About page for the Visual Studio Code Flask tutorial.
in the «title» and «content» blocks, respectively, then save the file.
- Repeat the previous step to create templates/contact.html using Contact us and
Contact page for the Visual Studio Code Flask tutorial.
in the two content blocks.
- In app.py , add functions for the /about/ and /contact/ routes that refer to their respective page templates. Also modify the home function to use the home.html template.
# Replace the existing home function with the one below @app.route("/") def home(): return render_template("home.html") # New functions @app.route("/about/") def about(): return render_template("about.html") @app.route("/contact/") def contact(): return render_template("contact.html")
Run the app
With all the page templates in place, save app.py , run the app, and open a browser to see the results. Navigate between the pages to verify that the page templates are properly extending the base template.

Note: If you’re not seeing the latest changes, you might need to do a hard refresh on the page to avoid seeing a cached file.
Optional activities
The following sections describe additional steps that you might find helpful in your work with Python and Visual Studio Code.
Create a requirements.txt file for the environment
When you share your app code through source control or some other means, it doesn’t make sense to copy all the files in a virtual environment because recipients can always recreate the environment themselves.
Accordingly, developers typically omit the virtual environment folder from source control and instead describe the app’s dependencies using a requirements.txt file.
Although you can create the file by hand, you can also use the pip freeze command to generate the file based on the exact libraries installed in the activated environment:
- With your chosen environment selected using the Python: Select Interpreter command, run the Terminal: Create New Terminal command ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) )) to open a terminal with that environment activated.
- In the terminal, run pip freeze > requirements.txt to create the requirements.txt file in your project folder.
Anyone (or any build server) that receives a copy of the project needs only to run the pip install -r requirements.txt command to reinstall the packages in the original environment. (The recipient still needs to create their own virtual environment, however.)
Note: pip freeze lists all the Python packages you have installed in the current environment, including packages you aren’t currently using. The command also lists packages with exact version numbers, which you might want to convert to ranges for more flexibility in the future. For more information, see Requirements Files in the pip command documentation.
Refactor the project to support further development
Throughout this Flask tutorial, all the app code is contained in a single app.py file. To allow for further development and to separate concerns, it’s helpful to refactor the pieces of app.py into separate files.
- In your project folder, create a folder for the app, such as hello_app , to separate its files from other project-level files like requirements.txt and the .vscode folder where VS Code stores settings and debug configuration files.
- Move the static and templates folders into hello_app , because these folders certainly contain app code.
- In the hello_app folder, create a file named views.py that contains the routings and the view functions:
from flask import Flask from flask import render_template from datetime import datetime from . import app @app.route("/") def home(): return render_template("home.html") @app.route("/about/") def about(): return render_template("about.html") @app.route("/contact/") def contact(): return render_template("contact.html") @app.route("/hello/") @app.route("/hello/") def hello_there(name = None): return render_template( "hello_there.html", name=name, date=datetime.now() ) @app.route("/api/data") def get_data(): return app.send_static_file("data.json")
import flask app = flask.Flask(__name__)
# Entry point for the application. from . import app # For application discovery by the 'flask' command. from . import views # For import side-effects of setting up routes.
"env": "FLASK_APP": "hello_app.webapp" >,

- Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use $env:FLASK_APP=webapp if you’re using PowerShell, or set FLASK_APP=webapp if you’re using Command Prompt.
- Navigate into the hello_app folder, then launch the program using python -m flask run .
Create a container for a Flask app using the Docker extension
The Docker extension makes it easy to build, manage, and deploy containerized applications from Visual Studio Code. If you’re interested in learning how to create a Python container for the Flask app developed in this tutorial, check out the Python in a container tutorial, which will walk you through how to:
- Create a Dockerfile file describing a simple Python container.
- Build, run, and verify the functionality of a Flask app.
- Debug the app running in a container.
If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.
Next steps
Congratulations on completing this walkthrough of working with Flask in Visual Studio Code!
The completed code project from this tutorial can be found on GitHub: python-sample-vscode-flask-tutorial.
Because this tutorial has only scratched the surface of page templates, refer to the Jinja2 documentation for more information about templates. The Template Designer Documentation contains all the details on the template language. You might also want to review the official Flask tutorial as well as the documentation for Flask extensions.
To try your app on a production website, check out the tutorial Deploy Python apps to Azure App Service using Docker Containers. Azure also offers a standard container, App Service on Linux, to which you deploy web apps from within VS Code.
You may also want to review the following articles in the VS Code docs that are relevant to Python:
- Editing Python code
- Linting
- Managing Python environments
- Debugging Python
- Testing
