Visual studio code не видит python
В 2016-м году компания Microsoft представила миру свой новый редактор программного кода. В отличие от старшей сестры — полноценной IDE Visual Studio — VS Code получился куда более компактным и легковесным решением. Он разработан как кроссплатформенное ПО и может быть успешно установлен в системах Windows, Linux и macOS.
Бесплатность Visual Studio Code абсолютно не мешает ему обладать весьма богатым современным функционалом. VS Code имеет встроенный отладчик, позволяет работать с системами контроля версий, обеспечивает интеллектуальную подсветку синтаксиса, а также поддерживает целый ряд популярных языков программирования.
И хоть, за годы своего существования, VSCode зарекомендовал себя, в основном, как продукт для веб-разработки, в 2018 году появилось расширение " Python ", которое дало программистам многочисленные возможности для редактирования, отладки и тестирования кода на нашем любимом языке.
Установка VSCode
Поистине смешные системные требования Visual Studio Code обязательно порадуют владельцев старых машин.
Для полноценной работы редактору требуется всего лишь 1 ГБ оперативной памяти и процессор с частотой от 1.6 ГГц.
Такое сочетание лёгкости и функциональности действительно подкупает, а отсутствие в VS Code каких-либо "лагов" и "фризов" делают разработку ещё более приятным и увлекательным занятием.
Установка редактора никуда не отходит от данной парадигмы и тоже является весьма простым и понятным процессом.
Windows
Сначала нужно скачать с официального сайта установочный файл небольшого размера, а затем установить сам ВиЭс код, следуя подсказкам от мастера установки.
Linux
На сайте программы можно изучить способы инсталляции редактора на разные Linux-дистрибутивы, но здесь рассмотрим процесс установки для самого популярного из них — Ubuntu.
Установить VSCode можно несколькими способами:
Способ №1 : Самый простой способ — воспользоваться менеджером установки "Ubuntu Software".
sudo apt install ./.deb
macOS
Алгоритм установки редактора внутри яблочной операционной системы также не представляет собой ничего сложного:
- Сначала нужно скачать Visual Studio Code с официального сайта.
- Затем открыть список загрузок браузера и найти там VSCode-Darwin-Stable.zip .
- Нажмите на иконку увеличительного стекла, чтобы открыть архив.
- Перетащите Visual Studio Code.app в папку приложений, сделав ее доступной на панели запуска.
- Щёлкните правой кнопкой мыши по значку и выберите команду " Оставить в Dock ".
Настройка под Python
Установка расширения "Python"
Для начала работы с Python, нужно перейти на вкладку Extensions , что находится на панели слева, либо нажать Ctrl + Shift + X . Сделав это, набираем в строке поиска " Python ".
VS Code поддерживает, как вторую, так и третью версию языка, однако python интерпретатор на свою машину вам придётся поставить самостоятельно.
Если вы новичок и только начинаете работу с Python или же не имеете каких-то особых указаний на этот счёт, то лучшим выбором станет именно актуальная третья версия.
Вот краткий список основных возможностей расширения "Python":
- Автодополнение кода.
- Отладка.
- Поддержка сниппетов.
- Написание и проведение тестов.
- Использование менеджера пакетов Conda.
- Возможность создания виртуальных сред.
- Поддержка интерактивных вычисления на Jupyter Notebooks.
Выбор версии интерпретатора Python
После от вас потребуется совершить выбор версии интерпретатора внутри самого редактора (обычно VS code знает, где он расположен). Для этого:
- Откройте командную строку VSCode (Command Palette) комбинацией Ctrl + Shift + P .
- Начинайте печатать " Python: Select Interpreter ";
- После, выберите нужную версию интерпретатора.
Также выбрать версию можно в панели активности в левом нижнем углу:
Если вы хотите использовать pipenv в своем проекте:
- Установите pipenv командой pip install pipenv (или pip3 install pipenv );
- Выполните команду pipenv install ;
- Откройте " Command Palette ", напечатайте " Python: Select Interpreter " и из списка выберите нужную версию интерпретатор.
Работа в VS Code
Запуск редактора
Как и другие современные редакторы и среды разработки, VS Code фиксирует состояние на момент закрытия программы. При следующем запуске, он открывается в том же самом виде, в котором существовал до завершения работы.
Так как VSCode, в первую очередь — редактор, а не полновесная среда разработки, здесь нет особой привязки к проекту. Вы можете сходу создавать, открывать и редактировать нужные вам файлы. Достаточно, после запуска, нажать Open File или New File и можно начинать работу.
Интерфейс
Интерфейс программы разрабатывался в стремлении сделать его как можно более простым и интуитивно понятным. Дизайнеры постарались, как максимизировать пространство для редактора, так и оставить достаточно места для отображения проводника по вашему проекту.
Весь UI VSCode разделился, таким образом, на шесть областей:
- Область редактора — основная область для написания и редактирования вашего кода.
- Боковая панель — здесь содержатся различные представления (например проводник).
- Строка состояния — визуализирует рабочую информацию об открытом в данный момент файле.
- Командная панель — классическая главная панель с вкладками file, edit, go, run и так далее.
- Панель активности — область в крайнем левом углу, где находятся важные вспомогательные вкладки, вроде контроля версий, дебаггера и магазина расширений.
- Мультипанель — панель на которой располагается вывод отладку, информация об ошибках и предупреждениях, а также встроенный в VS Code терминал.
Запуск Python-кода (run)
Выполнить код можно несколькими способами. Самый простой — комбинацией Ctrl + Alt + N .
Также можно вызвать скрипт контекстным меню, выбрав строку " Run Python File in Terminal ".
Или нажав иконку " Run " в правом верхнем углу.
Отладка (debugger)
Возможность полноценной отладки — сильная сторона редактора. Чтобы перейти в режим отладки, нужно установить точку останова и нажать F5 .
Вся информация о текущем состоянии будет выводиться на панель дебаггера.
Слева откроется панель дебаггера с информацией о состоянии переменных (Variables), отслеживаемых переменных (Watch) и стеке вызова (Call stack).
Сверху расположена панель инструментов дебаггера.
Рассмотрим команды (слева направо):
- continue ( F5) — перемещает между breakpoint-ами;
- step over ( F10) — построчное (пошаговое) перемещение;
- step into ( F11) — построчное (пошаговое) перемещение c заходом в каждую вызываемую функцию;
- step out ( Shift + F11) — работает противоположно step into — выходит из вызванной функции, если в данный момент вы находитесь внутри неё. Далее работает как continue .
- restart ( Ctrl + Shift + F5) — начинаем отладку с начала.
- stop ( Shift + F5) — остановка и выход из режима отладки.
С отладкой разобрались 👌.
Тестирование (testing)
С поддержкой тестов у VS Code тоже всё в порядке, однако, по умолчанию тестирование отключено. Для его активации нужна небольшая настройка.
Сначала следует нажать комбинацию клавиш Ctrl + Shift + P и в так называемой палитре команд выбрать Python: Configure Tests .
Для выбора фреймворка для тестов, выполните комбинацию "Ctrl + Shift + P" и наберите "Python: Configure Tests"
Редактор предложит вам определить фреймворк (мы выбрали "pytest") и папку, содержащую тесты (мы выбрали ". Root directory").
Создадим новый файл с тестами ( test_app.py ) и запустим его, кликнув правой кнопкой мыши на этом файле и выбрав пункт " Run Current Test File ".
Чтобы увидеть результаты, необходимо открыть вкладку Output на панели, и в выпадающем меню выбрать пункт PythonTestLog .
Как мы видим, первый тест прошел успешно, а второй провалился.
Для удобства работы с тестами, установим расширение " Python Test Explorer for Visual Studio Code ".
Теперь информацию по тестам можно посмотрев, кликнув на левой панели " иконку с колбой ", предварительно запустив тесты.
Вкладка "test" (иконка с колбой в панели слева) откроет удобный проводник для запуска тестов и просмотра их состояния.
Для начала работы с системами контроля версий обратимся к вкладке Source Control , что находится на панели активности слева (или Ctrl + Shift + G ).
По умолчанию VS Code дружит с Git и GitHub
Поддержку других систем возможно настроить самостоятельно, установив соответствующие расширения.
Чтобы связать проект с github (или gitlab), сперва необходимо скачать на ваш ПК git (если ещё не скачан). VSCode автоматически определит его местоположение, и затем у вас появится возможность синхронизации.
Все основные и необходимые операции для контроля версий будут находиться прямиком внутри редактора: коммитить, пуллить, пушить, создавать бранчи и просматривать изменения вы можете, не выходя из VisualStudioCode.
А для удобного просмотра изменений в git, советую установить расширение " Git Graph ". После его установки, на панели " Source Control " появится новая кнопка, которая отобразит граф состояния (git log).
The Python interpreter is no longer displayed in the lower-left corner of the VS Code window. Trying to select the Python interpreter via the command palette fails (literally nothing happens). Trying to run Python file in terminal results in command 'python.execInTerminal' not found .
Expected behavior
Python interpreter version shown in lower-left corner of VS Code windows. Attempts to select Python interpreter display installed Python versions. Python files can be run in terminal.
Steps to reproduce:
Just open VS Code. Notice that the Python interpreter is not shown in the lower left.
Because all this stuff used to work in the recent past (like a few weeks ago at most), I tried to downgrade my installation to 1.27.2. That produced the same symptoms. I also tried VS Code exploration versions (I think 1.28 and 1.29), and these did not suffer the same problems. What I described under "expected behavior" worked in both exploration versions.
Output for Python in the Output panel ( View → Output , change the drop-down the upper-right of the Output panel to Python )
None. It's completely empty.
Output from Console under the Developer Tools panel (toggle Developer Tools on under Help )
The text was updated successfully, but these errors were encountered:
jkyeung commented Oct 17, 2018 •
I understand that you are extremely busy, but it would be kinda nice to at least receive confirmation from OP (that is, me) that your proposed solution works before closing the issue.
It so happens that I did see many issues where the advice was "uninstall the extension, restart VS Code, reinstall the extension". So I did try that before posting my issue. I should have mentioned that when I opened the issue, and I apologize for leaving that out. I did try this "remedy" several times. Even a few times where I installed a completely different version of VS Code, and then installed the extension.
None of them worked (except in the exploration versions, as I noted in the initial post). And, in good faith, I tried doing the uninstall extension, restart VS Code, reinstall extension one more time after your post, but unfortunately it didn't resolve the issue.
jkyeung commented Oct 18, 2018
For the record, this turned out to be a workspace issue.
I was trying to figure out what was different about my nonworking VS Code session and my working VS Code (exploration version) session, as well as my working stable-release VS Code session on a different computer. I happened to notice that the title bar in all the working sessions just consisted of the name of the open file, a space, a hyphen, another space, and the name of the editor (either 'Visual Studio Code' or 'Visual Studio Code - Exploration'); but the nonworking session also mentioned something about an unnamed or unsaved workspace between the open file and the editor name. (I forget the exact verbiage now, and I never took a screenshot of it.) After closing the workspace from the File menu and restarting VS Code, everything worked the way it had been.
I still don't really understand why things weren't working with that workspace open. I never purposely use explicit workspaces, and don't know what they do.
Hopefully this helps some future frustrated soul.
brettcannon commented Oct 18, 2018
[I edited your ✉️ ⬆️ to come off as more 😃 and less 😠 ]
So on this issue tracker, "closed" doesn't mean "closed forever" but instead means "closed because we think the issue has been taken care of, but we will re-open if we are wrong". In other words had you not resolved the problem yourself and a re-install didn't fix it I would have happily re-opened the issue and continued trying to figure out what was going on.
We also have a problem on this issue tracker where we ask people to try something and get back to us and the OP simply never replies again. So when we have a high enough level of confidence we know the solution we preemptively close knowing that if it didn't work the OP will leave a follow-up comment like you did, rather than have to leave this open and then check later if this issue has gone stale because our fixed work and the OP forgot to reply back.
I am really new to Python and just started the course "Python 3 basics by Sendtex (Link: https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ)".
- I am trying to use Python with Visual Studio Code.
- The downloaded version of Python is 3.6.4.
- I have installed the Python extension in Visual Studio Code and have followed the procedure.
However, I am not able to get any output. Below is the attached screenshot.
If I select Python it enters debugging mode. So, there isn't any output.
Save this file, then go to the Terminal tab at the bottom and type python hello.py and press Enter. This should run the code and show an Output.
@Guillaume Output Tab shows nothing. As you can see in the screenshot when I press run then a popup comes that too is shown in screenshot.
5 Answers 5
Notes
I recommend reviewing the official Visual Studio Code Python documentation and tutorial. That provides several of the basics, with running and debugging the "official" way.
There are multiple ways to configure built-in launches:
- When running or debugging Python in VS Code, there are a few options that you can change in your "launch.json" file. See this answer for more details.
Run or Debug with the built-in Python extension commands
You can run or debug using an icon and dropdown in the upper right of your editor window, when editing a python script file.
You may need to setup a run/debug configuration to use this (see below), or it may automatically step you through creating one.
The output will normally go to a new "Python" terminal in the "terminal" window (Ctrl-` to open it). See this answer for how to change that behavior.
Setting up a run/debug configuration
Easy option:
- Use the menu item ** Run/Add Configuration , and follow the prompts at the top of the VS Code window.
- Some of the additional details are shown below.
More involved option:
- Click the run/debug icon on the left vertical icon toolbar.
Updated Image (1/2022) - Changed from just 'Debug' to 'Run and Debug':
- Click the gear icon (or in the menu, use Run/Open Configurations), and in the middle at the top, Visual Studio Code will open a window titled "Select a debug configuration".
- The available options will depend on exactly how you have Visual Studio Code setup and configured
- There should at least be a "Python File" option with the Python extension installed. Select it.
Now your debug configuration box on the top left of the debug pane should say "Python: Current File":
Visual Studio Code will add a file to your current workspace or working folder called .vscode/launch.json , and opened it for edit.
Output from Console under the Developer Tools panel (toggle Developer Tools on under Help ; turn on source maps to make any tracebacks be useful by running Enable source map support for extension debugging )
There are similar errors for all installed versions of python(system, virtualenvs, gcc compiled, clang compiled, 2.7.X, 3.6.X, 3.7X)
The text was updated successfully, but these errors were encountered:
mrbell321 commented Apr 24, 2019
karrtikr commented Apr 24, 2019
While i look at the issue, can you please try rollbacking to the previous version as a temporary solution and see if that fixes the issue.
You can right-click the Python extension in the extension tab and select a different version to install
mrbell321 commented Apr 24, 2019
Hmm. well perhaps it is fixed.
prelude) I had previously used VS Code w/ Python(unknown extension version) without issue, but the hard drive failed.
- Setting up a new instance with latest version as of two days ago(11881 maybe), which is where I first discovered it. Thought it was my issue so I wiped everything relating to python and started over.
- Definitely an extension bug as initially filed(11881).
- Updated to 11987, reloaded, no change
- back to 3.6558, reloaded, no change,
- back to 6352, reloaded, no change,
- back to 2019.1.0, reloaded, fixed!
- Then you asked if a rollback would fix. I check the installed version and it's 11987 which I definitely did not intend to do.
So I'm not sure what happened when I initially updated to 11987 or how 2019.1.0 automatically jumped back to 11987, but it's working now.
Sorry for the extra work. If I run into the issue again, I'll get back to you.
karrtikr commented Apr 24, 2019
No problem. Can you please answer a few things,
Updated to 11987, reloaded, no change
- What steps did you use to initially update to 11987? What steps did you use to rollback to 6352?
- When you were rollbacking to previous version, did you check the installed version? Was it the one you intended?
mrbell321 commented Apr 24, 2019
No problem. Can you please answer a few things,
Updated to 11987, reloaded, no change
- What steps did you use to initially update to 11987? What steps did you use to rollback to 6352?
View->Extensions->Python->Gear icon->"Install another version" for both.
- When you were rollbacking to previous version, did you check the installed version? Was it the one you intended?
I did not really check in between, I guess. I naively assumed no errors meant it went through without a problem.
I also realize I don't know Code's extension updating policy default. I usually use PyCharm, but it's os heavy, I've been trying out Code. Does VS Code automatically update extensions to the latest version on a restart/reload? That's probably why rolling back didn't fix the issue. but not really why when I first went to 11987, it didn't seem to fix things.
I suspect PEBKAC.karrtikr commented Apr 24, 2019 •
Does VS Code automatically update extensions to the latest version on a restart/reload?
Yes, but users can disable it with a setting. See this.
Note even if you rollback or upgrade, you will have to reload the window to use that version. Maybe you didn't reload, due to which you were not able to use the latest version in the first place.
mrbell321 commented Apr 25, 2019 •
. and it's back to not working.
It was working before lunch(working all yesterday afternoon and this morning) but when I came back now it's saying to select an interpreter. Although this time at least I can see all of the expected interpreters, but selecting them has no real effect
You need to select a Python interpreter before you start debugging. Tip: click on "Select Python Interpreter" in the status bar.
and the same error messages in Developer tools:
Python Extension: Failed to parse interpreter information for '/Users/XXXX/venv/bin/python' with JSON Invalid -W option ignored: invalid action: '"once' SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse () at p.getInterpreterInformation (/Users/XXX/.vscode/extensions/ms-python.python-2019.4.11987/out/client/extension.js:83:293720)It's Version: 2019.4.11987
As far as I know, nothing changed on this system between leaving for lunch and coming back(. and yet. )
karrtikr commented Apr 26, 2019 •
. and it's back to not working.
It was working before lunch(working all yesterday afternoon and this morning) but when I came back now it's saying to select an interpreter. Although this time at least I can see all of the expected interpreters, but selecting them has no real effect
You need to select a Python interpreter before you start debugging. Tip: click on "Select Python Interpreter" in the status bar.
and the same error messages in Developer tools:
Python Extension: Failed to parse interpreter information for '/Users/XXX/PycharmProjects/TraceUpdater/venv/bin/python' with JSON Invalid -W option ignored: invalid action: '"once' SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse () at p.getInterpreterInformation (/Users/XXX/.vscode/extensions/ms-python.python-2019.4.11987/out/client/extension.js:83:293720)It's Version: 2019.4.11987
As far as I know, nothing changed on this system between leaving for lunch and coming back(. and yet. )
Does reinstalling and reloading the window help?
Unfortunately i can't reproduce this flaky behavior. Can you please try recreating the virtual environment/ selecting a different interpreter?mrbell321 commented Apr 26, 2019
Reinstalling/reloading doesn't help.
I didn't re-create the venv, but I tried the system installed interpreters(apple and brew) and other venvs (mostly from the brew install) and they all give the same result. All the interpreters seem to work fine in PyCharm and from the command line.What is the core error? is the "Unexpected token I in JSON. " bit or is it the "invalid action 'once'"? and what is the command(I assume it's a command line) that it's trying to run?
karrtikr commented Apr 26, 2019 •
This is the error block
jsonValue here is the output of the running the file,
So this seems like an issue with json.dumps , you can try reinstalling the python package json for your virtual environment interpreter, or reinstalling Python in the worst case. Please let me know how it goes.
mrbell321 commented Apr 26, 2019
Well this works without reinstalling json:
I'm not sure how to go about reinstalling json. isn't that just part of the python std libs? Unless you mean reinstall python from scratch.
I'll try a few more things next week, but I suspect that this is just my own issue, not a tool bug. Thanks for the help!karrtikr commented Apr 26, 2019
Anytime.
I am not sure if it's the part of std libs, best way to go about it is reinstalling python from scratch (maybe trying a different python version), and installing json if it's not available.
I suspect it's a PEBKAC as well.mrbell321 commented Apr 30, 2019
Well, I completely formatted my HD, reloaded Mojave, re-installed python3 with brew( brew install python ), created a new venv python -m venv ./venv and.
exact same issue!DonJayamanne commented Apr 30, 2019
Please could run the following in the terminal and provide the output:
/Users/mrbell/PycharmProjects/TraceUpdater/.venv/bin/python /Users/XXXX/.vscode/extensions/ms-python.python-2019.4.11881/pythonFiles/interpreterInfo.pyNote: The version number could be different (assuming the extension has auto updated).
DonJayamanne commented Apr 30, 2019
Also, do you have the following env variable defined PYTHONWARNINGS . Please could you print the contents of the above variable.
mrbell321 commented Apr 30, 2019 •
Slightly different paths on the new system so:
and I don't have anything defined for PYTHONWARNINGS
mrbell321 commented May 1, 2019
karrtikr commented May 3, 2019
Did you try installing a different version of Python? The reason i am asking this is to make sure that this is not an issue we face with 3.7.3.
mrbell321 commented May 3, 2019
Same problem with 3.6.8.
But if you look closely, that's reporting 3.6.8 in my venv. I didn't create a 3.6.8 venv, I just wanted to know if the vscode would pick up the system installed 3.6.8 interpreter.
Apparently a difference between the venv module and virualenv is that venv uses symlinks by default and virtualenv uses copies. I've been doing python for years and I've never noticed before(although, I guess the venv module is relatively new).So I deleted the existing venv-module-created-venv-folder and suddenly vscode can see all of the interpreters on the system. I created a new venv folder with virtualenv and vscode can also see all of the interpreters that way.
I recreated the venv folder with the venv module and all of the interpreters are gone again.It seems there's a bug w/ vscode-python and the venv module which manages on break ALL interpreters.
karrtikr commented May 4, 2019
Good observation. Can you please clarify the minimal steps to reproduce this for macOS?
Doe just creating a venv folder with the venv module breaks the interpreter search for you?mrbell321 commented May 6, 2019
Hmm. to get a clean set of minimal steps, I cannot reproduce the issue entirely. Instead, only the venv(symlink) interpreter reports the error in developer tools, but the others show up as cached and are still selectable and useable. This is how I tested that:
- Create a new project folder.
- Opened project folder in vscode
- Cmd-P > 'Select Python Interpreter'
- Create a venv folder with python3 -m venv venv
- Restart vscode
- Cmd-P > 'Select Python Interpreter'
Result -> All system installed interpreters are available but not the venv.
The venv/bin/python reports the error from earlier in Dev Tools - Delete and re-create venv with virtualenv -p python3 venv
- Restart vscode
- Cmd-P > 'Select Python Interpreter'
Result -> System Interpreters remain available AND the venv interpreter is now available. - Delete and re-create venv with -m venv
- Restart vscode
- Cmd-P > 'Select Python Interpreter'
Result -> System Interpreters remain available AND the venv interpreter is gone again with the error in Dev Tools.
Last week, approximately the same process would lose all interpreters when using -m venv so I'll have to do some digging to find out what changed between then and now.
DonJayamanne commented May 7, 2019
I'm sorry for the inconvenience this issue has caused and the time taken to get to the bottom of this.
I'd like to try something, something we probably should have done early on:
- Open the file /Users/***/.vscode/extensions/ms-python.python-2019.***/pythonFiles/interpreterInfo.py
- Edit the file (contents provided further below)
- Run VS Code, and when it fails, then get the contents of the log.log file and upload it here.
Here's what I'd like to get out of this:
- Why is the code failing
- Have a look at any arguments passed to the above python file
- Have a look at the environment variables when the python file is running
- Dump all exceptions
** New contents for interpreterInfo.py :
Please review the environment variables in the log.log file before uploading the contents
mrbell321 commented May 13, 2019
So I ran this twice, this is the 2nd result(I accidentally overwrote the first try). Interestingly(or irritatingly) the results I saw were different. Here was my workflow:
- Launch vscode to see if there was an update
- close vscode
- Update interpreterInfo.py as per previous post
- Launch vscode
- Select interpreter.
The first run showed the system installed interpreters and even a virtualenv from another project, but not the currently open folder. - Copy log.log to my desktop for archival purposes.
karrtikr commented May 14, 2019
Thanks a lot for cooperating. However looking at the log,
- The code seems to run just fine, for .venv as well, which should imply that you should not be getting the earlier error.
- Can you please confirm that you see the earlier error, and please provide the log file just after you see this error,
Python Extension: Failed to parse interpreter information for '/Users/XXXX/venv/bin/python' with JSON Invalid -W option ignored: invalid action: '"once' SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse () at p.getInterpreterInformation (/Users/XXX/.vscode/extensions/ms-python.python-2019.4.11987/out/client/extension.js:83:293720)
** Please try this as the new content for interpreterInfo.py :
karrtikr commented Jun 21, 2019
Closing as no further response was provided.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Сегодня немного о моих мытарствах с VS Code и его настройкой для нормальной работы с Python разных версий. Сразу оговорюсь, что всё это настраивалось под меня, опыта у меня мало и вообще это большей частью “for fun”.
Редактор правда очень крутой, мощный (“навороченнее” какого-нибудь sublime text) и при этом очень лёгкий (запускается и работает шустрее PyCharm’a). Во всяком случае на мой неопытный взгляд (хотя авторитетные бобры тоже используют). Предполагается, что Python (2.x или 3.x, не важно) у вас уже установлен.
Итак.
После установки он попросит установить pylint, но это не сложно сделать прямо здесь же из консоли:
На этом как бы и всё, формальная часть выполнена. Но. Сегодня мне понадобилось протестить один и тот же код на работоспособность в Python 2.7 и 3.6. В Ubuntu проблем не возникало: жмём Ctrl+Shift+P, ищем в появившемся меню “Python: Select Workspace Enterpreter” и выбираем нужное из списка. В Win10 почему-то это не сработало так просто: хотя на компьютере точно установлены 2.7, 3.5 и 3.6. в списке только 2.7. Как добавить элементы в этот список я не нашёл, но нашёл способ изменить и дебагер и текущую используемую версию python в файлах настроек.
Дебагер.
Настраивается очень просто. При первом запуске дебагера вам будет предложено отредактировать конфигурацию, куда вам нужно дописать недостающие версии. Выглядит примерно так:
В этом блоке вам нужно изменить 2 строки: “name” (имя конфигурации)и “pythonPath” (путь до python.exe нужной версии). Не забудьте экранировать бэк-слэши:
Текущая версия интерпретатора.
Можно изменить в настройках приложения (файл settings.json). Нужно добавить следующее (Python 3.6):
Сохраняем настройки и теперь ваши скрипты будут исполняться интерпритатором Python 3.6.
Git
По дефолту в git пытается выгрузиться совершенно там ненужная папка .vscode, которая хранит разного рода служебную инфу. Чтобы этого не происходило создайте в корне проекта файлик .gitignore и добавьте в него следующее содержимое (.gitignore — чтобы игнорировался сам этот файл, да):
Приятные плюшки
Всё, указанное ниже, прописывается в файле settings.json
Я люблю всякие украшательства и использую встроенный пак иконок для разных типов файлов. Наглядно, стильно_модно_молодёжно.
Очень бывает удобно видеть количество пробелов перед строкой (особенно в python) и лишние пробелы между символами/словами:
Читайте также: