Visual studio code run code не работает

Как настроить Code Runner в Visual Studio Code для Python

Я установил Visual Studio Code 1.23.1 и добавил расширения — Python, Code Runner.

В Code Runner теперь я вижу символ «Выполнить код» (треугольник) и, выделяя его, вижу сочетание клавиш Ctrl + Alt + N. Но когда я пытаюсь использовать его для запуска кода, запрашивающего ввод пользователя, я могу не найти способ обеспечить ввод. Когда я пытаюсь ввести пользовательский ввод, я получаю сообщение об ошибке «Не удается редактировать в редакторе только для чтения». Я думаю, это потому, что мне не хватает некоторой части конфигурации для Code Runner, такой как настройка PATH или некоторые другие параметры рабочего пространства.

Вопрос . Пожалуйста, помогите мне определить, какие настройки мне понадобятся и как?

Я выбрал «Добавить Python 3.6 в PATH» при установке Python. Я приложил скриншоты для справки:

Примечание. Даже сейчас, когда я щелкаю правой кнопкой мыши и выбираю «Запуск файла Python в терминале» для той же программы, я могу точно ввести пользовательский ввод и получить ожидаемый результат.

3 ответа

Вы можете предоставить ввод, сказав код бегуна использовать терминал. Для этого есть параметр code-runner.runInTerminal , по умолчанию равный false, который можно установить в значение true.

Есть еще одна вещь, на которую следует обратить внимание, если вы используете командную строку Windows для терминала, такого как CMD или PowerShell. Если в каталоге вашего проекта есть пробелы (например, C: \ Example Test), вы получите ошибку. Чтобы это исправить, вам нужно добавить экранированные кавычки ( \» ) вокруг переменных пути к каталогу (обычно $dir или $workspaceRoot ), найденных в настройках code-runner.executorMap и <> в настройках пользователя.

Вот еще один альтернативный ответ, я думаю, что более точный .
Добавьте следующие настройки в ваш файл пользовательских настроек vscode:

Проверьте эту ссылку для некоторых полезных переменных: Справочник по переменным

Основная проблема заключается в том, что окно вывода, которое по умолчанию использует расширение для запуска кода, доступно только для чтения. Если вместо этого вы используете терминал, ваша программа сможет принимать ввод как обычно.

Вы можете настроить Code Runner для использования встроенного терминала вместо окна вывода, установив для параметра code-runner.runInTerminal значение true (по умолчанию установлено значение false). В файле settings.json он должен выглядеть следующим образом: «code-runner.runInTerminal»: true

Если вы хотите использовать вместо этого графический интерфейс, настройка должна выглядеть так, как только будет установлено значение true.

Если вы используете виртуальную среду вместо установки системного Python, вам также потребуется настроить второй параметр, чтобы он правильно работал с установленными модулями. Параметр code-runner.executorMap будет настраивать, что на самом деле делает бегун кода после нажатия клавиши run или использования сочетания клавиш Ctrl + Alt + N. По умолчанию кажется, что он просто вызывает интерпретатор python, добавленный в PATH.

Если вы измените настройку в файле settings.json на:

Тогда Code Runner будет использовать любое значение из переменной pythonPath. Вы можете установить это с помощью Python: выберите команду Interpreter из палитры команд (Ctrl + Shift + P). Таким образом, вы можете выбрать интерпретатор в вашей виртуальной среде и использовать его вместо того, который подключен к PATH по умолчанию.

Две вышеупомянутые настройки должны позволять вам: A) ввести ввод во встроенном терминале и B) выбрать, какой обработчик кода интерпретатора Python должен легко выполняться с использованием существующих команд.

Источник

Troubleshoot Terminal launch failures

If you are new to using the Visual Studio Code Integrated Terminal, you can learn more in the Integrated Terminal user guide. There you can read how to configure the terminal, as well as review answers to common questions.

Below are specific troubleshooting steps, if the user guide hasn’t helped you diagnose the launch failure. The troubleshooting steps, such as checking your settings and enabling logging, apply to all platforms that support VS Code; macOS, Linux, and Windows.

Note: If you’re on Windows, review the common issues on Windows section first.

Troubleshooting steps

To troubleshoot Integrated Terminal launch failures in Visual Studio Code, follow these steps to diagnose issues:

Читайте также:  Где отремонтировать заднюю балку пежо 206

Check your user settings. Review these terminal.integrated settings that could affect the launch:

  • terminal.integrated.shell. — The path of the shell that the terminal uses.
  • terminal.integrated.shellArgs. — The command-line arguments when launching the shell process.
  • terminal.integrated.cwd — The current working directory (cwd) for the shell process.
  • terminal.integrated.env. — Environment variables that will be added to the shell process.
  • terminal.integrated.inheritEnv — Whether new shells should inherit their environment from VS Code.
  • terminal.integrated.automationShell. — Shell path for automation-related terminal usage like tasks and debug.
  • terminal.integrated.splitCwd — Controls the current working directory a split terminal starts with.
  • terminal.integrated.windowsEnableConpty — Whether to use ConPTY for Windows terminal process communication.

You can review settings in the Settings editor (File > Preferences > Settings) and search for specific settings by the setting ID.

A quick way to check if you have changed settings that you might not be aware of, is to use the @modified filter in the Settings editor.

Most Integrated Terminal settings will need to be modified directly in your user settings.json JSON file. You can open settings.json via the Edit in settings.json link in the Settings editor or with the Preferences: Open Settings (JSON) command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).

Test your shell directly. Try running your designated integrated terminal shell outside VS Code from an external terminal or command prompt. Some terminal launch failures may be due to your shell installation and are not specific to VS Code. The exit codes displayed come from the shell and you may be able to diagnose shell issues by searching on the internet for the specific shell and exit code.

Use the most recent version of VS Code. Each VS Code monthly release has many updates and fixes and may include integrated terminal improvements. You can check your VS Code version via Help > About (on macOS Code > About Visual Studio Code). To find the latest version of VS Code, go to the VS Code release notes. You may also want to check that you have installed the latest version of your shell.

Enable trace logging. You can enable trace logging and capture a log when launching the terminal. Logging often reveals what is wrong as all arguments used to create the terminal process/pty are recorded. Bad shell names, arguments, or environment variables can cause the terminal to not launch. Keep this log for later if your problem isn’t solved.

Additional troubleshooting steps

If none of these steps helped solve the issue, you can also try:

  • Ask about it on Stack Overflow, often launch issues are related to environment setup and not a problem with VS Code.
  • If the terminal is being launched from an extension, report the issue to the extension by opening the issue reporter (Help > Report Issue) and set File On = «An Extension»
  • If you believe it to be a bug with VS Code, report the issue using the issue reporter (Help >Report Issue). The issue reporter will autofill relevant information, see Creating great terminal issues for what else to include in the report.
  • If you’re on Windows 10 1809 (build 17763) or below, the issue is related to the legacy «winpty» backend. Upgrading to Windows 1903 (build 18362) will move you onto the new «conpty» backend that is built by Microsoft and could fix your problem.

Exit codes

The exit codes displayed in the terminal launch failure notification are returned from the shell process and are not generated by VS Code. There are many available shells that can be used in the terminal and hundreds of possible exit codes. Try searching on the internet for your specific shell and exit code (for example, «PowerShell 4294901760») and you may find specific suggestions or known issues related to your terminal launch failure.

Common issues on Windows

Make sure compatibility mode is disabled

When upgrading to Windows 10, some apps may have compatibility mode turned on automatically. When this happens with VS Code, the terminal breaks as it does some low level things to enable the emulation it uses. You can check and disable compatibility mode by right-clicking on the VS Code executable and selecting properties, then uncheck the Run this program in compatibility mode option in the compatibility tab.

The terminal exited with code 1 on Windows 10 (with WSL as the default shell)

This can happen if Windows Subsystem for Linux (WSL) is not set up with a valid default Linux distribution.

Note: ‘docker-desktop-data’ is not a valid distribution.

  • Open PowerShell and enter wslconfig.exe /l to confirm WSL is installed correctly and list the currently available Linux distributions within your system. Confirm a valid distribution has (default) next to it.
  • To change the default distribution, enter wslconfig.exe /setdefault «distributionNameAsShownInList»

The terminal not working when running the 32-bit Windows client on 64-bit Windows?

The easy fix for this issue is to use the 64-bit version. If you must use the 32-bit version, you need to use the sysnative path when configuring your shell path instead of System32. Adding this setting should fix the issue:

A native exception occurred

Typically this error occurs due to anti-virus software intercepting and blocking the winpty/conpty components from creating the terminal process. To work around this error, you can exclude the following file from your anti-virus scanning:

Reporting this issue to the Anti-virus team can also help stamp out the issue all together.

Источник

Code Runner

Jun Han

Code Runner

Run code snippet or code file for multiple languages: C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, Scheme, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D, Lisp, Kit, V, SCSS, Sass, CUDA, Less, Fortran, Ring, and custom command

Sponsors


Increase your coding productivity with Tabnine’s AI code completions! Tabnine is a free powerful Artificial Intelligence assistant designed to help you code faster, reduce mistakes, and discover best coding practices — without ever leaving the comfort of VS Code.
Tabnine is trusted by more than a million developers worldwide. Get it now.

Eliminate context switching and costly distractions. Create and merge PRs and perform code reviews from inside your IDE while using jump-to-definition, your keybindings, and other IDE favorites. Learn more.


Track and prioritise tech debt and maintenance issues, straight from your IDE. Bookmark code while you work, organise TODOs and share codebase knowledge with your team. Try it out for free today.

Book for VS Code

WeChat Official Account

VS Code 的热门文章、使用技巧、插件推荐、插件开发攻略等,请关注“玩转VS Code”公众号!

Donation

If you like this extension, you could become a backer or sponsor via Patreon, donate via PayPal, or scan below QR code to donate via Alipay. Any amount is welcome. It will encourage me to make this extension better and better!

Features

  • Run code file of current active Text Editor
  • Run code file through context menu of file explorer
  • Run selected code snippet in Text Editor
  • Run code per Shebang
  • Run code per filename glob
  • Run custom command
  • Stop code running
  • View output in Output Window
  • Set default language to run
  • Select language to run
  • Support REPL by running code in Integrated Terminal

Usages

  • To run code:
    • use shortcut Ctrl+Alt+N
    • or press F1 and then select/type Run Code ,
    • or right click the Text Editor and then click Run Code in editor context menu
    • or click Run Code button in editor title menu
    • or click Run Code button in context menu of file explorer
  • To stop the running code:
    • use shortcut Ctrl+Alt+M
    • or press F1 and then select/type Stop Code Run
    • or click Stop Code Run button in editor title menu
    • or right click the Output Channel and then click Stop Code Run in context menu

  • To select language to run, use shortcut Ctrl+Alt+J , or press F1 and then select/type Run By Language , then type or select the language to run: e.g php, javascript, bat, shellscript.

  • To run custom command, then use shortcut Ctrl+Alt+K , or press F1 and then select/type Run Custom Command

Configuration

Make sure the executor PATH of each language is set in the environment variable. You could also add entry into code-runner.executorMap to set the executor PATH. e.g. To set the executor PATH for ruby, php and html:

Supported customized parameters

  • $workspaceRoot: The path of the folder opened in VS Code
  • $dir: The directory of the code file being run
  • $dirWithoutTrailingSlash: The directory of the code file being run without a trailing slash
  • $fullFileName: The full name of the code file being run
  • $fileName: The base name of the code file being run, that is the file without the directory
  • $fileNameWithoutExt: The base name of the code file being run without its extension
  • $driveLetter: The drive letter of the code file being run (Windows only)
  • $pythonPath: The path of Python interpreter (set by Python: Select Interpreter command)

Please take care of the back slash and the space in file path of the executor

  • Back slash: please use \\
  • If there ares spaces in file path, please use \» to surround your file path

You could set the executor per filename glob:

Besides, you could set the default language to run:

For the default language: It should be set with language id defined in VS Code. The languages you could set are java, c, cpp, javascript, php, python, perl, ruby, go, lua, groovy, powershell, bat, shellscript, fsharp, csharp, vbscript, typescript, coffeescript, swift, r, clojure, haxe, objective-c, rust, racket, ahk, autoit, kotlin, dart, pascal, haskell, nim, d, lisp

Also, you could set the executor per file extension:

To set the custom command to run:

To set the the working directory:

To set whether to clear previous output before each run (default is false):

To set whether to save all files before running (default is false):

To set whether to save the current file before running (default is false):

To set whether to show extra execution message like [Running] . and [Done] . (default is true):

[REPL support] To set whether to run code in Integrated Terminal (only support to run whole file in Integrated Terminal, neither untitled file nor code snippet) (default is false):

To set whether to preserve focus on code editor after code run is triggered (default is true, the code editor will keep focus; when it is false, Terminal or Output Channel will take focus):

code-runner.ignoreSelection : Whether to ignore selection to always run entire file. (Default is false)

code-runner.showRunIconInEditorTitleMenu : Whether to show ‘Run Code’ icon in editor title menu. (Default is true)

code-runner.showRunCommandInEditorContextMenu : Whether to show ‘Run Code’ command in editor context menu. (Default is true)

code-runner.showRunCommandInExplorerContextMenu : Whether to show ‘Run Code’ command in explorer context menu. (Default is true)

code-runner.showStopIconInEditorTitleMenu : Whether to show ‘Stop Code Run’ icon in editor title menu when code is running. (Default is true)

code-runner.terminalRoot : For Windows system, replaces the Windows style drive letter in the command with a Unix style root when using a custom shell as the terminal, like Bash or Cgywin. Example: Setting this to /mnt/ will replace C:\path with /mnt/c/path (Default is «»)

code-runner.temporaryFileName : Temporary file name used in running selected code snippet. When it is set as empty, the file name will be random. (Default is «tempCodeRunnerFile»)

code-runner.respectShebang : Whether to respect Shebang to run code. (Default is true)

About CWD Setting (current working directory)

  1. By default, use the code-runner.cwd setting
  2. If code-runner.cwd is not set and code-runner.fileDirectoryAsCwd is true , use the directory of the file to be executed
  3. If code-runner.cwd is not set and code-runner.fileDirectoryAsCwd is false , use the path of root folder that is open in VS Code
  4. If no folder is open, use the os temp folder
  • For Objective-C, it is only supported on macOS
  • To run C# script, you need to install scriptcs
  • To run TypeScript, you need to install ts-node
  • To run Clojure, you need to install Leiningen and lein-exec

Telemetry data

By default, telemetry data collection is turned on to understand user behavior to improve this extension. To disable it, update the settings.json as below:

Change Log

Issues

Submit the issues if you find any bug or have any suggestion.

Источник

Оцените статью