- Как настроить Code Runner в Visual Studio Code для Python
- 3 ответа
- code-runner not working #351
- Comments
- linhtto commented Aug 28, 2018
- marcdahan commented Aug 28, 2018
- linhtto commented Aug 28, 2018
- Visual Studio Code doesn’t run code
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged visual-studio-code c or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- VS Code Code Runner doesn’t work with virtualenvs
- 8 Answers 8
- Code Runner
- Jun Han
- Code Runner
- Sponsors
- Book for VS Code
- WeChat Official Account
- Donation
- Features
- Usages
- Configuration
- About CWD Setting (current working directory)
- Telemetry data
- Change Log
- Issues
Как настроить 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 должен легко выполняться с использованием существующих команд.
Источник
code-runner not working #351
Comments
linhtto commented Aug 28, 2018
I just installed VSCode recently (v1.26.1) on MacOS 10.13.6 and added code-runner. I tried it on a Python file and nothing happened upon executing «Run Code», either with anything selected or not. I then tried to choose Run Custom Command (the default one) and got this notification:
Running the contributed command:’code-runner.runCustomCommand’ failed.
The Output window is completely empty.
I’ve tried to uninstall and reinstall, and also restart my computer.
The text was updated successfully, but these errors were encountered:
marcdahan commented Aug 28, 2018
idem for me, but in my case a popup show : «command ‘code-runner.customCommand’ not found» when using the keybinding :
C:\Users\xxx\AppData\Roaming\Code\User\keybindings.json
<
«key»: «ctrl+s»,
«command»: «code-runner.customCommand»,
«when»: «editorTextFocus && editorLangId == ‘scss'»
>
and in : C:\Users\xxx\AppData\Roaming\Code\User\settings.json , I added :
«code-runner.customCommand»: «echo Marc»
but it’s working using ctrl+shift +p «run custom command»
linhtto commented Aug 28, 2018
For me it doesn’t work at all. If I try to run Python, for example, nothing happens and the OUTPUT window is empty. I tried to run the custom command in both ways, using the default keybinding ctrl + option + K and the Command Palette, I get the same popup notification. The difference is that the symbol on the notification is a red cross error sign if I run with the Command Palette, and a yellow warning sign if I run with the shortcut.
I already tried to disable all other extensions except this one to see if it makes a difference, but it doesn’t. Basically I’ve never been able to get Code Runner to work at all.
Источник
Visual Studio Code doesn’t run code
Why VS Code doesn’t want to run code when I use scanf() function to get user’s input knowing that without this function the code runs perfectly.
2 Answers 2
- CTRL+SHIFT+X
- Type in search box Code Runner
- Install the extension
- Than click on File — Preferences — Settings
- Type code run in search box.
- Scroll down until you find Code-runner: Run In Terminal. Check the box Wheather to run code in Integrated Terminal.
- Restart VS Code
first of all I’m a begginer in VS code so I will try my best to explain how I sort of fixed this «error». Hope this post still helps a lot of people.
What I think is happening is that this C program gets only compiled when you hit «Run Code». I’m not sure about this at all. The solution I found is that the right way to actually run your program is by «Start Debugging» (F5). Now when you go to the .json file where the configuartion for debugging is located. You simply need to change the line «externalConsole» and set it to «true». And that’s basically it. After that you simply Run your program with (F5). Keep in mind that if you change something in your original code you need to run it with «Run Code», (ctrl+alt+n) so that the uptades you do get saved and «compiled».
Line to change:
Not the answer you’re looking for? Browse other questions tagged visual-studio-code c or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.18.40487
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
VS Code Code Runner doesn’t work with virtualenvs
I can’t get Code Runner extension to work with virtualenvs. Whenever I try to run code that imports a library that is installed only in the virtualenv and not in the global Python installation I get an import error. Running the exact same code in terminal works.
I am on Windows 10 and I have Python 3.6.5 installed.
The precise error I am getting is:
8 Answers 8
I also faced same issue.
you have to enter your virtualenv path or you could use.
hope this helps you.
A possible solution would be to set the «code-runner.runInTerminal»: true in the VS Code settings, which is false by default. Doing so, Code Runner, will run the code in the shell that is configured using the «terminal.integrated.shell.windows» setting.
After that, run your script with Code Runner. This now opens a new terminal, where the python environment you have selected using VS Code’s Python: Select Interpreter will be activated automatically, before executing the code. (If the environment is not activated automatically, you can do this also manually, just make sure you do it in the terminal session that was opened by Code Runner.)
First approach:
First, I suggest to set executorMap like this:
by setting this, every time you change your Python interpreter version in VS Code, code-runner will use the same version to execute your code.
Second approach:
Another method I used before was to use a Shebang code in the first line like this:
code-runner is compatible with the Shebang command and it will execute your code with the version of Python that you have mentioned in the first line.
Источник
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)
- By default, use the code-runner.cwd setting
- If code-runner.cwd is not set and code-runner.fileDirectoryAsCwd is true , use the directory of the file to be executed
- 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
- 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.
Источник