Visual studio code cli команды
Visual Studio Code — популярная интегрированная среда разработки. Большой выбор плагинов, минимальный дизайн и поддержка кросс-платформ делают ее привлекательной для разработчиков всех уровней. В этом обучающем модуле основное внимание уделяется использованию плагина Remote-SSH для обеспечения удаленной разработки программного обеспечения. С этим плагином вы можете изменять файлы на локальной рабочей станции, при этом запуская такие задачи разработки, как выполнение программ, испытания узлов или статичный анализ на удаленном сервере.
Есть множество причин, по которым это может быть полезно для вас. Например, у вас может быть рабочая станция Windows, и вы хотите разрабатывать в Windows, но ваш код в конечном счете будет запускаться на Linux. Для обработки вам может потребоваться больше оперативной памяти или мощности процессора, чем у вашего текущего компьютера, или вы не захотите хранить код на личном компьютере из-за политики компании или желания оставить вашу рабочую станцию чистой.
В этом обучающем модуле вы научитесь активировать плагин Remote-SSH, настраивать Visual Studio Code для выполнения кода на удаленном сервере и выполнять код из локальной установки Visual Studio Code на удаленном сервере.
Предварительные требования
Для прохождения этого обучающего модуля вам потребуется следующее:
- Локальный компьютер для разработки, работающий под управлением Windows, MacOSX или Linux. Данный обучающий модуль не предназначен для устройств под управлением ChromeOS.
- Среда разработки Visual Studio Code, которую вы можете загрузить и установить с официального сайта.
- Сгенерированная пара ключей SSH:
- Если вы используете macOS или Linux, то можете перейти к 1-му шагу модуля Настройка ключей SSH в Ubuntu 18.04. Команды аналогичны, т.ч. не беспокойтесь о том, что в обучающем руководстве говорится, что они предназначены для Ubuntu 18.04.
- Если вы используете Windows, пройдите обучающий модуль Создание ключей SSH с помощью PuTTY в Windows для создания ключа SSH.
- Если вы используете DigitalOcean, то можете использовать руководство Выгрузка открытых ключей SSH в учетную запись DigitalOcean.
Шаг 1 — Установка плагина Remote-SSH
Extensions Marketplace — возможность загружать поддерживаемые и сторонние расширения для самых разных инструментов и языков программирования. Здесь вы найдете плагин Remote-SSH, после чего установите его.
С левой стороны IDE находится вертикальный ряд из пяти значков. Нижний значок, который выглядит как четыре квадрата в коробке с раскрывающимся правым верхним квадратом, — это значок Extensions Marketplace:
Также вы можете получить доступ к этому разделу, нажав Ctrl+Shift+X . После открытия этой страницы вы увидите предлагаемые плагины для загрузки и установки.
После открытия Extensions Marketplace введите Remote-SSH в панели Поиск расширений в Marketplace. Когда найдете плагин, выберите его и нажмите зеленую кнопку Установить для установки расширения.
Расширение установлено. Далее вы настроите расширение, чтобы подключиться к серверу.
Шаг 2 — Настройка плагина Remote-SSH и подключение к серверу
Теперь, когда у вас установлен плагин, вы можете настроить его для подключения к серверу. Для этого вам потребуются следующие сведения:
- IP-адрес сервера или имя хоста.
- Имя пользователя для подключения.
- Закрытый ключ, который вы будете использовать для аутентификации пользователя.
Вы будете использовать эту информацию для создания файла конфигурации SSH, который Visual Studio Code может использовать для SSH для синхронизации файлов на сервере и выполнения кода от вашего имени. Вы создадите эту конфигурацию, используя Visual Studio Code.
Следующая подсказка спросит, какой файл конфигурации вы хотите открыть. Если вы используете Windows, то увидите два местоположения: одно в персональном каталоге пользователя и одно в месте установки SSH. Используйте файл в каталоге пользователя при настройке сервера.
Выберите файл, и ваш редактор откроет файл config . Добавьте в файл следующий код , чтобы определить подключение к серверу, заменив выделенные разделы на информацию для вашего сервера:
Вот как работает этот файл конфигурации:
- Host : указывает имя вашего хоста. Это позволяет использовать короткое имя или аббревиатуру вместо полного IP-адреса либо имя хоста при подключении к серверу.
- HostName : фактическое имя хоста сервера, которое представляет собой либо IP-адрес, либо полностью квалифицированное доменное имя.
- User : пользователь, от имени которого вы хотите выполнить подключение.
- IdentityFile : путь к вашему закрытому ключу SSH. На системах Mac и Linux вы найдете ее в домашнем каталоге в скрытом каталоге .ssh , обычно id_rsa . Если вы используете Windows, у вас будет указано местоположение для сохранения этого файла при его создании с помощью putty-gen .
Определите соответствующие значения в вашем файле и сохраните файл.
Теперь Visual Studio Code настроен и готов подключиться к вашему серверу. Нажмите зеленую кнопку Открыть удаленное окно в нижнем левом углу и выберите Remote-SSH: подключиться к хосту…
После завершения всех этих действий все доступные и настроенные сервера появятся в выпадающем меню. Выберите из этого списка сервер, к которому вы хотите подключиться.
Если вы впервые подключились к этому серверу с компьютера, скорее всего, вы увидите диалог верификации SSH Fingerprint, как на следующем изображении:
Это необходимо, чтобы убедиться, что вы действительно подключаетесь к правильному серверу. Вы можете проверить это, войдя на свой сервер вручную и выполнив команду ssh-keygen -l -f /etc/ssh/ssh_host_key.pub для просмотра «отпечатка пальца» сервера. Если отпечаток тот же, что указан в Visual Studio Code, то вы действительно подключаетесь к правильному серверу, т.ч. можете нажать Продолжить.
Visual Studio Code по умолчанию открывает новое окно после создания нового подключения. Появится новое окно с экраном приветствия. Вы узнаете, что подключение прошло успешно, если увидите SSH: your_ip_address_or_hostname в зеленой коробке в нижнем левом углу. Это означает, что Visual Studio Code подключен и связывается с вашим удаленным сервером.
Теперь, когда вы подключены, вы можете выполнять команды и код из редактора.
Шаг 3 — Выполнение кода на удаленном сервере
Плагин Remote-SSH настроен, и теперь можно запустить какой-нибудь код на вашем удаленном компьютере. Откройте окно терминала, выбрав Терминал из панели навигации в верхней части окна Visual Studio, и нажмите Новый терминал. Также вы можете открыть терминал, нажав ``CTRL+Shift+```. Открывшийся терминал находится на вашем удаленном сервере, а не на локальном компьютере.
Когда терминал откроется, дайте следующую команду, чтобы посмотреть IP-адрес вашего сервера, чтобы убедиться, что вы подключены к удаленному серверу:
В своем терминале вы увидите следующее:
Чтобы протестировать способность запуска удаленного кода, создайте новый файл Python с именем hello.py в редакторе. После подключения к удаленному серверу все файлы, созданные при помощи Visual Studio Code, будут сохранены на этот сервер, а не на локальный компьютер.
Добавьте в файл следующие строчки:
Для запуска этой программы на вашем сервере откройте терминал в Visual Studio Code из меню навигации, или нажав CTRL+Shift+` . Поскольку этот терминал подключен к вашему удаленному серверу, выполните в терминале следующую команду для выполнения вашей программы hello.py :
Отобразится вывод вашей программы.
Также вы можете выполнить файл из контекстного меню Отладка, выбрав Запуск без отладки.
Заключение
Теперь у вас есть Visual Studio Code, настроенный для разработки на удаленном сервере с помощью SSH. Удаленное исполнение при помощи IDE обеспечивает множество преимуществ, в том числе способность быстро тестировать процесс выполнения вашего кода на различных операционных системах и с различными техническими спецификациями оборудования. Если у вас есть подключение к Интернету, вы можете подключаться к вашему серверу и работать над вашим кодом с любого компьютера, а также можете заниматься разработкой в среде Linux, даже если будете использовать Windows в качестве основной операционной системы.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Visual Studio Code has a powerful command-line interface built-in that lets you control how you launch the editor. You can open files, install extensions, change the display language, and output diagnostics through command-line options (switches).
If you are looking for how to run command-line tools inside VS Code, see the Integrated Terminal.
Command line help
To get an overview of the VS Code command-line interface, open a terminal or command prompt and type code --help . You will see the version, usage example, and list of command line options.
Launching from command line
You can launch VS Code from the command line to quickly open a file, folder, or project. Typically, you open VS Code within the context of a folder. To do this, from an open terminal or command prompt, navigate to your project folder and type code . :
Note: Users on macOS must first run a command (Shell Command: Install 'code' command in PATH) to add VS Code executable to the PATH environment variable. Read the macOS setup guide for help.
Windows and Linux installations should add the VS Code binaries location to your system path. If this isn't the case, you can manually add the location to the Path environment variable ( $PATH on Linux). For example, on Windows, VS Code is installed under AppData\Local\Programs\Microsoft VS Code\bin . To review platform-specific setup instructions, see Setup.
Insiders: If you are using the VS Code Insiders preview, you launch your Insiders build with code-insiders .
Core CLI options
Here are optional arguments you can use when starting VS Code at the command line via code :
Argument Description -h or --help Print usage -v or --version Print VS Code version (for example, 1.22.2), GitHub commit ID, and architecture (for example, x64). -n or --new-window Opens a new session of VS Code instead of restoring the previous session (default). -r or --reuse-window Forces opening a file or folder in the last active window. -g or --goto When used with file:line[:character], opens a file at a specific line and optional character position. This argument is provided since some operating systems permit : in a file name. -d or --diff Open a file difference editor. Requires two file paths as arguments. -w or --wait Wait for the files to be closed before returning. --locale Set the display language (locale) for the VS Code session. (for example, en-US or zh-TW ) Opening Files and Folders
Sometimes you will want to open or create a file. If the specified file does not exist, VS Code will create them for you along with any new intermediate folders:
For both files and folders, you can use absolute or relative paths. Relative paths are relative to the current directory of the command prompt where you run code .
If you specify more than one file at the command line, VS Code will open only a single instance.
If you specify more than one folder at the command line, VS Code will create a Multi-root Workspace including each folder.
Argument Description file Name of a file to open. If the file doesn't exist, it will be created and marked as edited. You can specify multiple files by separating each file name with a space. file:line[:character] Used with the -g argument. Name of a file to open at the specified line and optional character position. You can specify multiple files in this manner, but you must use the -g argument (once) before using the file:line[:character] specifier. folder Name of a folder to open. You can specify multiple folders and a new Multi-root Workspace is created. Working with extensions
You can install and manage VS Code extensions from the command line.
Argument Description --install-extension Install an extension. Provide the full extension name publisher.extension as an argument. Use --force argument to avoid prompts. --uninstall-extension Uninstall an extension. Provide the full extension name publisher.extension as an argument. --disable-extensions Disable all installed extensions. Extensions will still be visible in the Disabled section of the Extensions view but they will never be activated. --list-extensions List the installed extensions. --show-versions Show versions of installed extensions, when using --list-extensions --enable-proposed-api Enables proposed api features for an extension. Provide the full extension name publisher.extension as an argument. Advanced CLI options
There are several CLI options that help with reproducing errors and advanced setup.
Argument Description --extensions-dir Set the root path for extensions. Has no effect in Portable Mode. --user-data-dir Specifies the directory that user data is kept in, useful when running as root. Has no effect in Portable Mode. -s, --status Print process usage and diagnostics information. -p, --performance Start with the Developer: Startup Performance command enabled. --disable-gpu Disable GPU hardware acceleration. --verbose Print verbose output (implies --wait ). --prof-startup Run CPU profiler during startup. --upload-logs Uploads logs from current session to a secure endpoint. Multi-root --add Add folder(s) to the last active window for a multi-root workspace. Opening VS Code with URLs
You can also open projects and files using the platform's URL handling mechanism. Use the following URL formats to:
Open a file to line and column
You can use the URL in applications such as browsers or file explorers that can parse and redirect the URL. For example, on Windows, you could pass a vscode:// URL directly to the Windows Explorer or to the command line as start vscode:// .
Note: If you are using VS Code Insiders builds, the URL prefix is vscode-insiders:// .
Next steps
Read on to find out about:
-
- Run command-line tools from inside VS Code. - Learn the basics of the VS Code editor. - VS Code lets you quickly understand and move through your source code.
Common questions
'code' is not recognized as an internal or external command
Your OS cannot find the VS Code binary code on its path. The VS Code Windows and Linux installations should have installed VS Code on your path. Try uninstalling and reinstalling VS Code. If code is still not found, consult the platform-specific setup topics for Windows and Linux.
On macOS, you need to manually run the Shell Command: Install 'code' command in PATH command (available through the Command Palette ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Consult the macOS specific setup topic for details.
How do I get access to a command line (terminal) from within VS Code?
VS Code has an Integrated Terminal where you can run command-line tools from within VS Code.
Can I specify the settings location for VS Code in order to have a portable version?
Not directly through the command line, but VS Code has a Portable Mode, which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
Read the Commands Guide for how to use the commands API.
The following is a sample of how to open a new folder in VS Code:
Commands
vscode.executeDocumentHighlights - Execute document highlight provider.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of DocumentHighlight-instances.
vscode.executeDocumentSymbolProvider - Execute document symbol provider.
- uri - Uri of a text document
- (returns) - A promise that resolves to an array of SymbolInformation and DocumentSymbol instances.
vscode.executeFormatDocumentProvider - Execute document format provider.
- uri - Uri of a text document
- options - Formatting options
- (returns) - A promise that resolves to an array of TextEdits.
vscode.executeFormatRangeProvider - Execute range format provider.
- uri - Uri of a text document
- range - A range in a text document
- options - Formatting options
- (returns) - A promise that resolves to an array of TextEdits.
vscode.executeFormatOnTypeProvider - Execute format on type provider.
- uri - Uri of a text document
- position - A position in a text document
- ch - Trigger character
- options - Formatting options
- (returns) - A promise that resolves to an array of TextEdits.
vscode.executeDefinitionProvider - Execute all definition providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Location or LocationLink instances.
vscode.executeTypeDefinitionProvider - Execute all type definition providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Location or LocationLink instances.
vscode.executeDeclarationProvider - Execute all declaration providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Location or LocationLink instances.
vscode.executeImplementationProvider - Execute all implementation providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Location or LocationLink instances.
vscode.executeReferenceProvider - Execute all reference providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Location-instances.
vscode.executeHoverProvider - Execute all hover providers.
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A promise that resolves to an array of Hover-instances.
vscode.executeSelectionRangeProvider - Execute selection range provider.
- uri - Uri of a text document
- position - Position in a text document
- (returns) - A promise that resolves to an array of ranges.
vscode.executeWorkspaceSymbolProvider - Execute all workspace symbol providers.
- query - Search string
- (returns) - A promise that resolves to an array of SymbolInformation-instances.
vscode.prepareCallHierarchy - Prepare call hierarchy at a position inside a document
- uri - Uri of a text document
- position - A position in a text document
- (returns) - A CallHierarchyItem or undefined
vscode.provideIncomingCalls - Compute incoming calls for an item
- item - A call hierarchy item
- (returns) - A CallHierarchyItem or undefined
vscode.provideOutgoingCalls - Compute outgoing calls for an item
- item - A call hierarchy item
- (returns) - A CallHierarchyItem or undefined
vscode.executeDocumentRenameProvider - Execute rename provider.
- uri - Uri of a text document
- position - A position in a text document
- newName - The new symbol name
- (returns) - A promise that resolves to a WorkspaceEdit.
vscode.executeLinkProvider - Execute document link provider.
- uri - Uri of a text document
- linkResolveCount - (optional) Number of links that should be resolved, only when links are unresolved.
- (returns) - A promise that resolves to an array of DocumentLink-instances.
vscode.provideDocumentSemanticTokensLegend - Provide semantic tokens legend for a document
- uri - Uri of a text document
- (returns) - A promise that resolves to SemanticTokensLegend.
vscode.provideDocumentSemanticTokens - Provide semantic tokens for a document
- uri - Uri of a text document
- (returns) - A promise that resolves to SemanticTokens.
vscode.provideDocumentRangeSemanticTokensLegend - Provide semantic tokens legend for a document range
- uri - Uri of a text document
- (returns) - A promise that resolves to SemanticTokensLegend.
vscode.provideDocumentRangeSemanticTokens - Provide semantic tokens for a document range
- uri - Uri of a text document
- range - A range in a text document
- (returns) - A promise that resolves to SemanticTokens.
vscode.executeCompletionItemProvider - Execute completion item provider.
- uri - Uri of a text document
- position - A position in a text document
- triggerCharacter - (optional) Trigger completion when the user types the character, like , or (
- itemResolveCount - (optional) Number of completions to resolve (too large numbers slow down completions)
- (returns) - A promise that resolves to a CompletionList-instance.
vscode.executeSignatureHelpProvider - Execute signature help provider.
- uri - Uri of a text document
- position - A position in a text document
- triggerCharacter - (optional) Trigger signature help when the user types the character, like , or (
- (returns) - A promise that resolves to SignatureHelp.
vscode.executeCodeLensProvider - Execute code lens provider.
- uri - Uri of a text document
- itemResolveCount - (optional) Number of lenses that should be resolved and returned. Will only return resolved lenses, will impact performance)
- (returns) - A promise that resolves to an array of CodeLens-instances.
vscode.executeCodeActionProvider - Execute code action provider.
- uri - Uri of a text document
- rangeOrSelection - Range in a text document. Some refactoring provider requires Selection object.
- kind - (optional) Code action kind to return code actions for
- itemResolveCount - (optional) Number of code actions to resolve (too large numbers slow down code actions)
- (returns) - A promise that resolves to an array of Command-instances.
vscode.executeDocumentColorProvider - Execute document color provider.
- uri - Uri of a text document
- (returns) - A promise that resolves to an array of ColorInformation objects.
vscode.executeColorPresentationProvider - Execute color presentation provider.
- color - The color to show and insert
- context - Context object with uri and range
- (returns) - A promise that resolves to an array of ColorPresentation objects.
vscode.executeInlayHintProvider - Execute inlay hints provider
- uri - Uri of a text document
- range - A range in a text document
- (returns) - A promise that resolves to an array of Inlay objects
vscode.resolveNotebookContentProviders - Resolve Notebook Content Providers
- (returns) - A promise that resolves to an array of NotebookContentProvider static info objects.
- uri - Uri of a text document
- columnOrOptions - (optional) Either the column in which to open or editor options, see vscode.TextDocumentShowOptions
- label - (optional)
- (returns) - no result
vscode.openWith - Opens the provided resource with a specific editor.
- resource - Resource to open
- viewId - Custom editor view id or 'default' to use VS Code's default editor
- columnOrOptions - (optional) Either the column in which to open or editor options, see vscode.TextDocumentShowOptions
- (returns) - no result
vscode.diff - Opens the provided resources in the diff editor to compare their contents.
- left - Left-hand side resource of the diff editor
- right - Right-hand side resource of the diff editor
- title - (optional) Human readable title for the diff editor
- columnOrOptions - (optional) Either the column in which to open or editor options, see vscode.TextDocumentShowOptions
- (returns) - no result
vscode.removeFromRecentlyOpened - Removes an entry with the given path from the recently opened list.
vscode.openIssueReporter - Opens the issue reporter with the provided extension id as the selected source
- extensionId - extensionId to report an issue on
cursorMove - Move cursor to a logical position in the view
- Cursor move argument object - Property-value pairs that can be passed through this argument:
- 'to': A mandatory logical position value providing where to move the cursor.
- 'by': Unit to move. Default is computed based on 'to' value.
- 'value': Number of units to move. Default is '1'.
- 'select': If 'true' makes the selection. Default is 'false'.
editorScroll - Scroll editor in the given direction
- Editor scroll argument object - Property-value pairs that can be passed through this argument:
- 'to': A mandatory direction value.
- 'by': Unit to move. Default is computed based on 'to' value.
- 'value': Number of units to move. Default is '1'.
- 'revealCursor': If 'true' reveals the cursor if it is outside view port.
revealLine - Reveal the given line at the given logical position
- Reveal line argument object - Property-value pairs that can be passed through this argument:
- 'lineNumber': A mandatory line number value.
- 'at': Logical position at which line has to be revealed.
editor.unfold - Unfold the content in the editor
- Unfold editor argument - Property-value pairs that can be passed through this argument:
- 'levels': Number of levels to unfold. If not set, defaults to 1.
- 'direction': If 'up', unfold given number of levels up otherwise unfolds down.
- 'selectionLines': The start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.
editor.fold - Fold the content in the editor
- Fold editor argument - Property-value pairs that can be passed through this argument:
- 'levels': Number of levels to fold.
- 'direction': If 'up', folds given number of levels up otherwise folds down.
- 'selectionLines': The start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used. If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.
editor.action.goToLocations - Go to locations from a position in a file
- uri - The text document in which to start
- position - The position at which to start
- locations - An array of locations.
- multiple - Define what to do when having multiple results, either peek , gotoAndPeek , or `goto
- noResultsMessage - Human readable message that shows when locations is empty.
editor.action.peekLocations - Peek locations from a position in a file
- uri - The text document in which to start
- position - The position at which to start
- locations - An array of locations.
- multiple - Define what to do when having multiple results, either peek , gotoAndPeek , or `goto
workbench.action.quickOpen - Quick access
- prefix - String value indicating the value to fill into the quick access input field when opening
moveActiveEditor - Move the active editor by tabs or groups
- Active editor move argument - Argument Properties:
- 'to': String value providing where to move.
- 'by': String value providing the unit for move (by tab or by group).
- 'value': Number value providing how many positions or an absolute position to move.
vscode.setEditorLayout - Sets the editor layout.
The layout is described as object with an initial (optional) orientation (0 = horizontal, 1 = vertical) and an array of editor groups within. Each editor group can have a size and another array of editor groups that will be laid out orthogonal to the orientation. If editor group sizes are provided, their sum must be 1 to be applied per row or column. Example for a 2x2 grid: < orientation: 0, groups: [< groups: [<>, <>], size: 0.5 >, < groups: [<>, <>], size: 0.5 >] >
notebook.cell.execute - Execute Cell
- range - The cell range
- uri - The document uri
notebook.cell.cancelExecution - Stop Cell Execution
- range - The cell range
- uri - The document uri
notebook.execute - Execute Notebook
notebook.cancelExecution - Cancel Notebook Execution
notebook.fold - Fold Cell
notebook.unfold - Unfold Cell
notebook.selectKernel - Notebook Kernel Args
search.action.openNewEditor - Open a new search editor. Arguments passed can include variables like $.
search.action.openEditor - Open a new search editor. Arguments passed can include variables like $.
search.action.openNewEditorToSide - Open a new search editor. Arguments passed can include variables like $.
vscode.openFolder - Open a folder or workspace in the current window or new window depending on the newWindow argument. Note that opening in the same window will shutdown the current extension host process and start a new one on the given folder/workspace unless the newWindow parameter is set to true.
- uri - (optional) Uri of the folder or workspace file to open. If not provided, a native dialog will ask the user for the folder
- options - (optional) Options. Object with the following properties: forceNewWindow : Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window. noRecentEntry : Whether the opened URI will appear in the 'Open Recent' list. Defaults to true. Note, for backward compatibility, options can also be of type boolean, representing the forceNewWindow setting.
workbench.extensions.installExtension - Install the given extension
workbench.extensions.uninstallExtension - Uninstall the given extension
workbench.extensions.search - Search for a specific extension
workbench.action.files.newUntitledFile - New Untitled File
workbench.action.findInFiles - Open the search viewlet
Simple commands
Simple commands that do not require parameters can be found in the Keyboard Shortcuts list in the default keybindings.json file. The unbound commands are listed in a comment block at the bottom of the file.
To review keybindings.json :
Windows, Linux: File > Preferences > Keyboard Shortcuts > keybindings.json link
macOS: Code > Preferences > Keyboard Shortcuts > keybindings.json link
Visual Studio Code is a free, open-source, and cross-platform text editor developed primarily by Microsoft. It uses web technologies such as JavaScript and CSS, which has helped facilitate a large ecosystem of community-created plugins to extend its functionality into many different programming languages and features.
In this tutorial, you’ll install the Visual Studio Code command line interface and learn how to use it to open files and directories, compare changes between files, and install extensions.
Prerequisites
To complete this tutorial, you’ll need to have Visual Studio Code installed. Please refer to the official Setting up Visual Studio Code documentation to find out how to install Code for your platform.
Installing the Visual Studio Code Command Line Interface
You may need to install the Visual Studio Code command line interface before using it. To do so, first launch the normal Visual Studio Code graphical interface. If this is your first time opening the app, the default screen will have a icon bar along the left, and a default welcome tab:
Visual Studio Code provides a built-in command to install its command line interface. Bring up Code’s Command Palette by typing Command+Shift+P on Mac, or Control+Shift+P on Windows and Linux:
This will open a prompt near the top of your Code window. Type shell command into the prompt. It should autocomplete to the correct command which will read Shell Command: Install 'code' command in PATH :
Press ENTER to run the highlighted command. You may be prompted to enter your administrator credentials to finish the installation process.
You now have the code command line command installed.
Verify that the install was successful by running code with the --version flag:
If your output includes a version string, you’ve successfully installed the Visual Studio Code command line interface. The next few sections will show you a few ways to use it.
Opening Files with the code Command
Running the code command with one or more filenames will open those files in the Visual Studio Code GUI:
This will open the file1 file in Code.
This will open all markdown ( .md ) files in the current directory in Code.
By default, the files will be opened in an existing Code window if one is available. Use the --new-window flag to force Visual Studio Code to open a new window for the specified files.
Opening a Directory with the code Command
Use the code command followed by one or more directory names to open the directories in a new Visual Studio Code window:
Code will open a new window for the directories. Use the --reuse-window flag to tell Code to reuse the existing frontmost window instead.
Opening a .code-workspace Workspace File with the code Command
Opening a workspace file with the code command works similar to opening directories:
This will open the example workspace in a new window, unless you reuse an existing window by adding the --reuse-window flag.
Installing an Extension Using the code Command
You can install Visual Studio Code extensions using the code command line tool as well. To do so, you’ll first need to know the extension’s unique identifier. To find this information, first navigate to the extension’s page on the Visual Studio Marketplace.
For instance, here is the page for the Jupyter Notebook extension:
Notice the itemName parameter in the address. This parameter’s value, ms-toolsai.jupyter , is this extension’s unique identifier.
You can also find this information on the Marketplace page itself, towards the bottom of the right-hand column in the More info section:
Once you have this unique id, you can use it with code --install-extension to install the extension:
Use the same id with the --uninstall-extension flag to uninstall the extension.
Showing the Differences Between Two Files Using the code Command
To show a standard split-screen diff that will highlight the additions, deletions, and changes between two files, use the --diff flag:
Similar to opening files, this will reuse the frontmost window by default, if one exists. To force a new window to open, use the --new-window flag.
Piping stdin Into Visual Studio Code Using the code Command
An important feature of most command line shells is the ability to pipe (or send) the output of one command to the input of the next. In the following command line, notice the | pipe character connecting the ls ~ command to code - :
This will execute the ls command on the ~ directory, which is a shortcut for the current user’s home directory. The output from ls will be a list of files and directories in your home directory. This will be sent to the code command, where the single - indicates that it should read the piped in text instead of a file.
code will output some information about the temporary file that it has created to hold the input:
Then this file will open up in the Code GUI interface:
This command will continue to wait indefinitely for more input. Press CTRL+C to have code stop listening and return you to your shell.
Add the --new-window flag to force Code to open a new window for the input.
Conclusion
In this tutorial you installed Visual Studio Code’s code command line tool, and used it to open files and directories, compare files, and install extensions.
To learn more about the code command, you can run its --help function:
You can also refer to the official Visual Studio Code command line documentation or take a look at our VS Code tag page for more Visual Studio Code tutorials, tech talks, and Q&A.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Visual Studio включает две оболочки командной строки для разработчиков, командную строку и экземпляр PowerShell, как показано ниже.
Командная строка разработчика для Visual Studio — стандартная командная строка с определенными переменными среды, упрощающая работу с инструментами разработки. Доступно с версии Visual Studio 2015.
PowerShell для разработчиков Visual Studio — более функциональное средство, чем командная строка. Например, в нем можно передать результат одной команды (называемой cmdlet ) в другой cmdlet. В этой оболочке доступны те же переменные среды, что и в Командной строке разработчика. Доступно с версии Visual Studio 2019.
Начиная с версии 16.5, в Visual Studio 2019 доступен встроенный терминал, где можно работать как с Командной строкой разработчика, так и с PowerShell для разработчиков. Можно открыть несколько вкладок для каждой оболочки. Терминал Visual Studio построен на основе Терминала Windows. Чтобы открыть терминал в Visual Studio, выберите элементы Вид > Терминал.
При запуске в Visual Studio одной из оболочек как отдельного приложения или в окне терминала открывается каталог текущего решения (если оно загружено). Это упрощает выполнение команд для решения или его проектов.
В обеих оболочках заданы определенные переменные среды. Это упрощает работу с инструментами командной строки. Открыв эти оболочки, можно выполнять команды для различных служебных программ, не указывая их расположения.
Запуск в Visual Studio
Выполните следующие действия, чтобы открыть в Visual Studio Командную строку разработчика или PowerShell для разработчиков:
Запустите Visual Studio.
В строке меню выберите элементы Инструменты > Командная строка > Командная строка разработчика или PowerShell для разработчиков.
Запуск из меню Windows
Другой способ запуска оболочек — из меню "Пуск". В зависимости от версии Visual Studio, дополнительно установленных пакетов SDK и рабочих нагрузок может иметься несколько вариантов командных строк.
Windows 11
Выберите для приложения результат, связанный с текстом поиска.
Windows 10
Разверните папку Visual Studio 2019 или Visual Studio 2022.
Если вы используете Visual Studio 2019, выберите Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. Если используется Visual Studio 2022, выберите Командная строка разработчика для VS 2022 или PowerShell для разработчиков для VS 2022.
Кроме того, вы можете начать вводить имя оболочки в поле поиска на панели задач и выбрать нужный результат, так как в списке результатов начнут отображаться найденные совпадения.
Windows 8.1
Перейдите на экран Пуск, нажав клавишу с логотипом Windows на клавиатуре, например.
На начальном экране нажмите Ctrl+Tab, чтобы открыть список приложений, а затем нажмите V. Появится список, включающий все установленные командные строки Visual Studio.
Если вы используете Visual Studio 2019, выберите Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. Если используется Visual Studio 2022, выберите Командная строка разработчика для VS 2022 или PowerShell для разработчиков для VS 2022.
Windows 7
Выберите Пуск а затем разверните Все программы.
Выберите элементы Visual Studio 2019 > Инструменты Visual Studio > Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. (Если вы используете Visual Studio 2022, найдите те же элементы, которые содержат "2022" вместо "2019".)
Если установлены другие пакеты SDK, например, пакет SDK для Windows 10 или предыдущих версий, могут появиться дополнительные командные строки. Требуемая версия командной строки указана в документации по соответствующим инструментам.
Запуск из обозревателя файлов
Обычно ярлыки для установленных оболочек помещаются в папку меню "Пуск" для Visual Studio, например в %ProgramData%\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools. Но если поиск командной строки не дает ожидаемых результатов, попробуйте вручную найти нужные файлы на компьютере.
Командная строка разработчика
Выполните поиск файла командной строки (VsDevCmd.bat) или перейдите в папку "Инструменты" Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools — путь зависит от версии Visual Studio, выпуска и расположения установки).
Когда вы найдете файл командной строки, откройте его. Для этого введите следующую команду в стандартном окне командной строки:
Кроме того, вы можете ввести следующую команду в диалоговом окне Windows Выполнить:
Не забудьте изменить путь в соответствии с используемой версией Visual Studio.
PowerShell для разработчиков
Найдите файл скрипта PowerShell с именем Launch-VsDevShell.ps1 или перейдите в папку "Инструменты" Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools). Путь зависит от версии, выпуска и расположения установки Visual Studio. После этого выполните следующую команду в командной строке Windows PowerShell или PowerShell 6:
По умолчанию PowerShell для разработчиков запускается с конфигурацией для той версии Visual Studio, путь установки к которой указан в файле Launch-VsDevShell.ps1.
Чтобы выполнить cmdlet, нужно задать политику выполнения.
Скрипт Launch-VsDevShell.ps1 находит модуль PowerShell Microsoft.VisualStudio.DevShell.dll в каталоге установки Visual Studio, скачивает модуль и вызывает командлет Enter-VsDevShell cmdlet. Установленные ярлыки, как в меню "Пуск", будут загружать модуль и вызывать cmdlet напрямую. Использование Launch-VsDevShell.ps1 — это рекомендуемый способ инициализации PowerShell для разработчиков в интерактивном режиме или автоматизации сборки скрипта.
аргументов командной строки;
Можно использовать аргументы командной строки для любой из оболочек, «Командная строка разработчика» или «PowerShell для разработчика».
Целевая архитектура и архитектура узла
Для средств сборки (таких как компилятор C++), которые создают выходные данные, предназначенные для конкретных архитектур ЦП, оболочки разработки можно настроить с помощью определенного аргумента командной строки. Архитектуру двоичных файлов средства сборки также можно настроить с помощью аргументов командной строки. Это полезно, если архитектура компьютера сборки отличается от целевой архитектуры.
Начиная с Visual Studio 2022, для msbuild по умолчанию будет использоваться 64-разрядный двоичный файл msbuild.exe, независимо от архитектуры узла.
Shell Аргумент Командная строка разработчика -arch= Командная строка разработчика -host_arch= PowerShell для разработчиков -Arch PowerShell для разработчиков -HostArch Аргументы -Arch и -HostArch в PowerShell для разработчика доступны только начиная с версии Visual Studio 2022 с обновлением 17.1.
Ниже приведена таблица со списком поддерживаемых архитектур. В нем также указано, можно ли их использовать для аргументов целевой архитектуры или архитектуры узла.
Архитектура Целевая архитектура Архитектура узла x86 По умолчанию По умолчанию amd64 Да Да arm Да Нет arm64 Да Нет Если задана только целевая архитектура, оболочки будут пытаться сопоставить с ней архитектуру узла. Поэтому, если настроена только целевая архитектура со значением, не поддерживаемым для архитектуры узла, могут возникнуть ошибки.
Примеры
Запустите Командную строку разработчика для Visual Studio 2019 Community Edition на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для 64-разрядной архитектуры:
Запустите Командную строку разработчика для Visual Studio 2019 Community Edition на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для ARM:
Запустите PowerShell для разработчиков для версии Community Edition Visual Studio 2022 17.1 или более поздней версии на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для arm64:
SkipAutomaticLocation
Начальный каталог оболочки PowerShell для разработчика — это расположение проекта Visual Studio. Этот язык по умолчанию переопределяет все остальные пути, например к рабочему каталогу. Такое поведение можно отключить с помощью аргумента командной строки -SkipAutomaticLocation . Это полезно, если, например, вы хотите, чтобы в оболочке использовался текущий каталог после инициализации.
Расположение проекта можно настроить в меню Средства > Параметры > Проекты &и решения > Расположение проекта.
Аргументы командной строки -Arch , -HostArch и -SkipAutomaticLocation поддерживаются скриптом Launch-VsDevShell.ps1 и командлетом Enter-VsDevShell cmdlet.
Читайте также: