Managing source code within the context of a project requires being able to navigate and maintain files, work within the appropriate Python environment, and maintain changes with source control. Each of these tasks is available in Visual Studio Code as either standard functionality or with the installation of an extension. In this chapter, the core features for managing projects are explored in a chatbot application created with the ChatBotAI library. (To learn more about the ChatBotAI library, visit pypi.org/project/chatbotAI
.) The application uses the Wikipedia library to search for information from Wikipedia articles. (To learn more about the Wikipedia library, visit pypi.org/project/wikipedia/
.) The exercises within this chapter are completed within the Wikipeida_Chatbot
folder.
In Visual Studio Code, working with files and folders goes beyond simply accessing a file. You can open a complete project in the editor and manage multiple files across subfolders simultaneously. Once a project is opened in the editor, Visual Studio Code provides helpful features for navigating and searching across folders. The Explorer view displays the contents of an opened project, thus providing easy access to manage and open files in the editor.
To manage a project in Visual Studio Code, first open its folder in the editor using one of these methods:
code .
to open in Visual Studio Code.Try It Out: Use your preferred method to open the Wikipedia_Chatbot folder.
When a folder is opened, the Explorer view displays the folder contents. Files can be opened with either a single-click or a double-click; however, the outcome differs for each action. A single-click opens a file in a tab within the editor. If you happen to single-click another file, the initial file tab is replaced with the subsequent file. If edits are made to a file in an editor tab, single-clicking a file in the Explorer view opens the file in a new tab.
A double-click opens the file in an editor tab. A subsequent single-click on another file in the editor opens the file in a new tab in the editor. The benefit of a double-click is that you are able to open multiple files within a project in new editor tabs without the need to edit any files within the editor.
Try It Out: In the Explorer view, open the README.md
file. Next, navigate to the examples
folder and open the Example.py
file to display in the editor (see Figure 4.3).
If there are files or folders that you'd like Visual Studio Code to hide in the Explorer and search feature, you can define the pattern with the File: Exclude setting (see Figure 4.4).
Navigation history is saved each time you navigate between files in the editor. If there are multiple files opened in the editor, you can view all files in an editor group with the keyboard shortcut Ctrl+Tab. A list of opened files displays at the top of the editor. You can change the active file by holding Ctrl while pressing Tab to select the file and then release Ctrl to apply the selection. The keyboard shortcut Ctrl+Shift+Tab navigates the list in reverse order when there are many files open.
Try It Out: Press Ctrl+Tab to change the active file (see Figure 4.5).
You can also navigate files in a folder using the Breadcrumbs. The Breadcrumbs display can be found at the top of the editor and shows the file path. Selecting a breadcrumb in the path displays a drop-down with the level's siblings. You can then select a sibling to navigate to other folders and files (see Figure 4.6).
The Command Palette command Focus Breadcrumbs is used to interact with breadcrumbs. When used, the last element in the breadcrumb trail is selected, and a drop-down opens that enables you to navigate to a sibling file or folder. Use the up and down arrow keys to select a sibling element. To navigate to the children elements of a sibling, use the left and right arrow keys (see Figure 4.7).
Searching across files in an opened folder can be done quickly with the Search view (Cmd+Shift+F/Ctrl+Shift+F). Search results display below the search bar as you type in the search term. Search results are grouped into files containing the search term. The search term results (see Figure 4.8) include the term's total number of occurrences in each file and the respective location(s). You can expand a file to see a preview of all occurrences within the file and single-click an occurrence to view in the editor.
Try It Out: Search for the term wikipedia across all files in the Wikipedia_Chatbot folder. Once found, click an occurrence in the Example.py
file to view in the editor.
Example.py
file to view the file and term location in the editor (see Figure 4.10)
You can filter your search by selecting whether you want the results to match the case (Option+Cmd+C/Alt+C) or match the whole word (Option+Cmd+W/Alt+W). In addition to the keyboard shortcuts, each filter can be accessed using the icons in the search bar (see Figure 4.11).
The search feature supports regular expression searching as well. To toggle regular expression searching, click the Use Regular Expression icon in the search bar (see Figure 4.11, C) or use the keyboard shortcut Option+Cmd+R/Alt+R.
Search results could also be replaced by another term. Click the arrow next to the search field, which opens the Replace field (see Figure 4.12, A). This feature enables you to preserve the case (see Figure 4.12, B) and replace all (see Figure 4.12, C) instances of the term in the project.
To specify which files to include or exclude from search results, click the Toggle Search Details (see Figure 4.13) icon below the search field. Enter the name of the files in the appropriate field.
Search results could also display in the editor by clicking Open In Editor (see Figure 4.14). When selected, search results display in a new tab, which lists every instance of the search term and the respective location by line in a scrollable format.
There's also the ability to search for a term directly from the editor. The keyboard shortcut Cmd+F/Ctrl+F opens a search bar inside the active tab (see Figure 4.15). Enter the search term into the tab to search the file. The editor search bar includes some similar commands from the Search view. In addition, there is a Find In Selection as indicated by the triple line icon.
Visual Studio Code refreshes when a folder is closed. You can close a file or folder in the editor in various ways.
The Python extension for Visual Studio Code provides integration features for working with global, virtual, and conda environments. Although a global environment provides the fastest way to get started with writing a Python program, it is recommended to manage projects in their own isolated virtual or conda environments to avoid library version conflicts across different projects. Using isolated environments also helps you clearly understand what libraries are used with each specific project.
To select an environment, run the Python: Select Interpreter command in the Command Palette. The Command Palette provides a list of Python interpreters. In the interpreter list, virtual and conda environments are indicated by either env or conda in parentheses. Global environments are presented without the parentheses. See Figure 4.16.
Visual Studio Code automatically detects when you create a new virtual environment and prompts you to select whether the new virtual environment should be selected for the workspace (see Figure 4.17). If selected, Visual Studio Code saves the path to the Python interpreter in the virtual environment to the Workspace settings.
Before you can create a conda environment, conda must be set as the default integrated terminal shell to use conda commands in Visual Studio Code. The shell can be set in the User settings.
settings.json
file, set terminal.integrated.shell.<platform>
, in addition to terminal.integrated.shellArgs.<platform>
. For example, for Windows, the entry would be as follows:
"terminal.integrated.shell.windows": "C:\Windows\System32\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K", "C:\<path to conda installation>\Scripts\activate.bat C:\<path to conda installation>"],
When selecting an interpreter, Visual Studio Code automatically detects existing conda environments that contain a Python interpreter. If you create a conda environment while Visual Studio Code is running, you must first reload the window to refresh the environment list that is available when selecting a Python interpreter. To refresh the window, run the command Developer: Reload Window.
It may take a moment for the conda environment to appear in the list. If the conda environment doesn't at first appear, try the command again in 15 seconds.
Try It Out: Create either a virtual or conda environment for the Wikipedia_Chatbot project. After the isolated environment is activated, install ChatBotAI and Wikipedia.
pip install chatbotAI, pip install wikipedia
conda install -c anaconda chatbotAI, conda install -c anaconda wikiedpia
Run Examples.py
to try the application; see Figure 4.19. When the application starts, the chatbot greets and continues to ask a series of questions related to your response. To make a Wikipedia inquiry, ask the chatbot Who/What is <query> (e.g., What is Visual Studio Code). Assuming that there is a Wikipedia page for the topic, the chatbot returns the introductory paragraph for the topic. If there is no relevant Wikipedia article, the chatbot returns with the string I don't know about <query>.
To stop the program, enter quit
.
Visual Studio Code is equipped with integrated source control that enables you to track and manage changes to code. Source control also provides a way to collaborate with others across a project by connecting to a remote repository, such as a repository on GitHub. Although the editor comes with the Git source control manager (SCM) built in, you can install an additional SCM from the Extension Marketplace. Git version 2.0.0 or newer must be installed to use Git features. To install or update Git, visit git-scm.com/download
.
The Source Control view provides version control information for your project, such as Changes, Staged Changes, and Merge Changes. The Source Control icon always indicates an overview of how many files have been changed in your repository (see Figure 4.20).
If you do not have a folder opened, the Source Control view instructs you to either open a folder that contains a Git repository or clone a repository. See Figure 4.21.
The Status Bar contains a Git status bar that displays the checked-out branch (see Figure 4.22, A) and either a Synchronize Changes or Publish action (see Figure 4.22, B). Additional information regarding each action is explained in the later section titled “Remotes.”
Visual Studio Code detects changes made within the Visual Studio Code UI in addition to changes made through the command-line interface (CLI). Therefore, you can run CLI commands in another shell or in the Visual Studio Code integrated terminal given that Visual Studio Code syncs with the current state. If you're entering commands within the Visual Studio Code UI, you can open the Git output window to view the commands. To access the Git output window, navigate to View ➪ Output (Ctrl+Cmd+U/Ctrl+Shift+U) and select Git from the Output window drop-down menu (see Figure 4.23).
The Source Code view displays a “No source control providers registered” message if Visual Studio Code doesn't detect an existing Git repository. To initialize a repository, click the Initialize Repository command that appears in the view. Alternatively, run the Git: Initialize Repository command from the Command Palette.
When you initialize a repository, Visual Studio Code creates the necessary Git repository metadata files and shows your files as files that have not yet been committed for the first time. Such files are referred to as untracked changes (indicated by a U icon) ready to be staged.
Try It Out: Initialize a repository for chatbot.
The Views And More Actions (see Figure 4.25) icon within the Source Control view provides a list of options for changing how the files within the Changes section are viewed and sorted. The View and Sort menu option provides the option to view changes as either a list or a tree. The default setting is to view as a list. If the Changes section is set to view as a list, you could sort the list by name, path, or status.
Try it Out: Change the view of changes to view them as a tree (see Figure 4.26).
You can conveniently commit changes for your project from the Source Control view. The Changes section within the view displays all changes made within the project. Next to each file is the Git status indicated by a letter.
You can discard all changes (see Figure 4.27) or stage all changes using the icons in the Changes header. To view the icons, hover over the header.
If you hover over a file within the Changes section, you're given the option to either open the file (A), discard the changes (B) or stage the changes (C). See Figure 4.28.
Once a change is staged, the file is moved to the Staged Changes section. If you hover over a file within the Staged Changes section, you're given the option to either open the file (A) or unstage the changes (B). See Figure 4.29.
Commit messages are entered in the Message bar (see Figure 4.30). To commit the changes, either press Cmd+Enter/Ctrl+Enter or select the Commit icon.
Before committing project files to the repository, it's likely that you'd want to ignore some files such as the virtual environment folder or any file which contains environment variables. Visual Studio Code provides two quick ways to add files to a .gitignore
file. After the .gitignore
file is created, you can add files directly from either the Source Control view or the Command Palette. When a file is added to .gitignore
, Visual Studio Code opens the .gitignore
file in a new tab.
Before adding a file to .gitignore
, the file must be unstaged. To add a file to .gitignore
from the Source Control view, right-click the file and select Add To .gitignore (see Figure 4.31).
Alternatively, you could add a file from the Command Palette with the command Git: Add To .gitignore. Before you run the command, ensure that the file is active in the editor.
Try It Out: Stage and commit the files in the Wikipedia_Chatbot project to the master branch.
.gitignore
(e.g. the virtual environment folder).When collaborating with others, code changes, such as new features or bug fixes, are often created on a branch. Branches enable collaborators to branch from the codebase and complete their work in an isolated environment independent of others. With Git, changes made on a branch can be merged with the codebase or master branch. In Visual Studio Code, there are two ways to create a new branch:
When you create a new branch, the branch is automatically checked out. Checking out a branch updates the files in the working directory to match the version stored in that branch. When a branch is checked out, Git records all new commits on the branch. There are two ways to manually check out a branch:
Try It Out: Create a new branch for the Wikipedia_Chatbot project. In Example.py
, change the string assigned to the first_question
variable to Hi, what would you like to know?
.
vscode-chatbot-exercises
. See Figure 4.36.
vscode-chatbot-exercises
branch is checked out in the Status Bar (see Figure 4.37).
first_question
variable to Hi, what would you like to know?
Visual Studio Code also supports repositories connected to a remote, such as GitHub. You can push, pull, and sync a branch to its origin all within the editor. The aforementioned Git commands are available in the Source Control view within the More Actions menu. See Figure 4.38.
The Synchronize Changes action in the Git status bar pulls remote changes down to your local repository and then pushes local commits to the remote repository. If there is no remote repository configured, the Publish action is enabled, which lets you publish the current branch to a remote.
Visual Studio Code can also fetch changes from a remote. The benefit of this feature is that the editor can show you how many changes your local repository is ahead or behind the remote. Although this feature is disabled by default, you can modify the setting git.autofetch
to true
to enable it.
If you're making changes to a file within a folder that is a Git repository, Visual Studio code adds annotations to the left of the editor window—referred to as the gutter (see Figure 4.39). There are three visual indicators:
Changes are compared in the Diff editor. To view diffs for a file, select the file in the Source Control view. The Diff editor opens in a new tab with a side-by-side view of the diffs (see Figure 4.40).
You can toggle to the inline view by opening the More Actions menu at the top of the Diff editor and selecting Toggle Inline View (see Figure 4.41).
The Previous Change (Ctrl+Option+F5/Shift+Alt+F3) and Next Change (Option+F5/Alt+F3) icons are used to navigate the diffs. See Figure 4.42.
Try It Out: In the Example.py
file, change the string assigned to the first_question
variable to Hi, what would you like to know?
. Save the file.
from chatbot import Chat, register_call
import wikipedia
import os
import warnings
warnings.filterwarnings("ignore")
@register_call("whoIs")
def who_is(session, query):
try:
return wikipedia.summary(query)
except Exception:
for new_query in wikipedia.search(query):
try:
return wikipedia.summary(new_query)
except Exception:
pass
return "I don't know about "+query
first_question = "Hi, what would you like to know?"
chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Example.template"))
chat.converse(first_question)
Select the Example.py
file in the Source Control view to view the diffs in the Diffs editor (see Figure 4.43) and then commit the changes.
You can also manually select any two files to view diffs:
As changes are committed, the Status Bar lists the total number of commits to push to the origin. Selecting the status bar item executes the task to push and pull to origin. See Figure 4.44.
After the commits are pushed, the status bar item changes to display only the Synchronize Changes icon (see Figure 4.45).
The pull request workflow is supported in Visual Studio Code with pull request extensions. One such extension is the GitHub Pull Requests and Issues extension. Pull request extensions enable you to review, comment, and merge pull requests all within the editor for a remote (see Figure 4.46).
The Live Share extension enables sharing and collaboration across multiple users but within Visual Studio Code. A host shares a project in Visual Studio Code with guests who can remotely view or edit the project. Collaborators are able to work together simultaneously across a project, thus eliminating the back-and-forth tasks for commits, pushes, pull requests, and merge conflicts. Live Share provides full-feature functionality for all participants regardless of whether they join a session in the Visual Studio Code desktop client (on any operating system) or a web browser. In the end, a collaborative session results in a single commit. Either a Microsoft or GitHub account is required to participate in a Live Share session. Sharing or joining the session itself occurs within seconds and maintains access to your preferred environment configurations and settings.
Download the Live Share extension from the Extension Marketplace. The extension page includes requirements that are necessary to use the extension.
Once it's installed, reload and wait for dependencies to download and install. You can check the status of the installation within the Status Bar. After installation is complete, a few additional UI elements and features are added to the editor.
For security purposes, sign-in is required to use Live Share. The following account types are required:
@
outlook.com
)To sign in, click the Live Share status bar item. A notification appears that requests you to log in via the browser. Click Launch Sign In to open the browser to a sign-in page. Alternatively, you can run the command Live Share: Sign In With Browser to access the sign-in page. Once signed in, close the browser and return to Visual Studio Code.
If you signed in without joining a session, the Status Bar reflects that you are signed in (see Figure 4.49) and displays an icon for you to share a project.
If you signed in after accessing a link to join a session, the Status Bar initially reflects that you are joining a session followed by a change in state to indicate that you've joined the session.
A host provides access to a Live Share session by sharing an invite link with guests. Before you can generate an invite link, the project must first be opened in Visual Studio Code. Hosts have complete flexibility in regard to which files/folders are visible for guests. In addition, hosts can select whether the session enables edits or is read-only.
The steps to share a project are as follows:
After sharing, a notification appears to let you know that the invite link has been copied to your clipboard (see Figure 4.50). The link is always available for access by clicking on the status bar item and selecting Invite Others (Copy Link). The notification also enables you to set the session to read-only. A read-only session prevents others from editing the project. This setting may be useful for a session with external guests you may not trust or when pair programming.
Once the session is active, the Status Bar reflects that a collaboration session is active (see Figure 4.52) and provides a total count of guests. Guests are automatically taken to the file you're editing once they join the session.
When you are done sharing the project, stop sharing by clicking the Stop Collaboration Session icon in the Live Share view (see Figure 4.53). Once sharing has stopped, all guests are notified that the session has ended. At that point, guests no longer have access to the project, and any temp files are automatically cleaned up.
Guests receive access to a Live Share session by navigating to the invite link shared by the host. Guests can join a session either via a web browser or via the Visual Studio Code desktop client (see Figure 4.54). Joining via the browser is ideal for guests who may not have the necessary tools installed and provides quicker access to the session. Browser access is optimal for short-term guests who wouldn't need to install Visual Studio Code locally. The browser is also an alternative for collaborators working on a tablet, smartphone, or any other device that cannot run Visual Studio Code, whereas joining with Visual Studio Code is ideal for guests who may already have the editor running or who are experiencing issues joining with the invite link.
To join a session via the web browser, click the invite link provided by the host. The link takes you to a web page that provides the option to continue to the browser. Once you join the session, you have full access to all Visual Studio Code editing features. To leave the session, close the browser window.
Joining a session through the desktop client requires that the Live Share extension is already installed in the editor. After signing into Live Share, navigate to the Live Share view in the Activity Bar and click the Join Collaboration Session icon (see Figure 4.55).
You can paste the invite link URL and press Enter to confirm (see Figure 4.56). Once confirmed, you are connected to the session, and the Status Bar is updated to reflect both that you've joined and the total count of guests.
To leave the session, close the Visual Studio Code window (see Figure 4.57). Alternatively, if you'd prefer to keep the window open, click the Leave Collaboration Session icon in the Live Share view.
During the session, everyone has the ability to simultaneously edit code (if the session is not read-only) and to navigate the project's files and folders. Both the host and guests can see each other's edits and selections in real time. Visual Studio Code displays a flag next to a guest's cursor on hover or when they edit, highlight, or move their cursor (see Figure 4.58).
Following enables you to follow everything the host or another guest does in the editor. You can follow a person by selecting their name in the participant's list. If you are following someone, the circle next to their name is filled in, and the line number in their active file displays as well (see Figure 4.59).
You could also follow someone by clicking the pin icon in the right corner of the editor group (see Figure 4.60). If more than one other person is in the session, you will be asked to select the participant you want to follow.
You can stop following someone by selecting the pin icon again or with the keyboard shortcut Cmd+Alt+F/Ctrl+Alt+F. Furthermore, following automatically stops if you do any of the following:
Hosts can also share terminals with guests (see Figure 4.61). Sharing a terminal enables guests to run commands on their own without the need to rely on the host. This may be helpful in cases where it may be more efficient for a guest to run a series of commands rather than walk the host through the commands to run within the terminal. Although terminals are not shared by default, the host can share a terminal by clicking the Share Terminal icon or entry in the Live Share view. Before the terminal is shared, Visual Studio Code provides the option to select one of the following two access modes:
Visual Studio Code provides a new shared terminal once the access mode is selected. When a shared terminal session ends, all guests are disconnected. Hosts can stop a shared terminal session one of three ways:
exit
into the terminalIn this chapter, you learned how to do the following:
You're now prepared to manage a Python project and collaborate with others in Visual Studio Code.
18.222.196.175