Как подключить питон к wing

Wing Python IDE

The Intelligent Development Environment for Python

Navigation

Tutorial: Setting Python Path

However, in some cases code will depend on a different path provided either by setting the environment variable PYTHONPATH before starting Python, or by modifying sys.path at runtime before importing modules.

The configuration used here is for illustrative purposes only. You could run the example code without altering the Python Path by moving the path_example.py file to the same location as the example scripts.

Startup Environment

Wing uses its startup environment as the default environment for your Python code. As a result, if PYTHONPATH is set when you start Wing, it will also be used with your code. If this inherited path matches the needs of your code, then you don’t need to set Python Path in Wing. However, if you have different Python environments on your system or code with different path expectations, then you should set Python Path in the project so that switching projects will also switch to the correct environment.

Virtualenv and Anaconda Environments

You can also create a new virtualenv or Anaconda environment at the same time as creating a Wing project by selecting the Create New Virtualenv or Create New Anaconda Environment project types in the New Project dialog, accessed from the Project menu.

But don’t do this now; you’ll need the current project as you work through this tutorial.

Источник

Wing Python IDE

The Intelligent Development Environment for Python

Navigation

Wing Pro Quick Start Guide

This is a minimalist guide for getting started quickly with Wing Pro. For a more in-depth introduction, try the Tutorial.

Wing Pro is a light-weight yet powerful integrated development environment that was designed from the ground up for Python. Once you’re up to speed with Wing you should find that:

This is made possible through deep code analysis (both static and runtime), a focus on interactive development in the live runtime, high-level editing operations and refactoring, continuous early error detection, support for test-driven development, powerful always-on debugger, seamless support for remote and containerized development, and extreme configurability.

Let’s get started with Wing Pro!

Install Python

If you don’t already have Python on your system, install it now. Two good options are:

Install Wing

If you don’t already have Wing installed, download it now. For detailed installation instructions, see Installing Wing.

Start Wing

For more information, see Running Wing.

Wing Pro requires a license to run. If you don’t have a license, you can obtain a 30-day trial the first time you start it. Wing Personal and Wing 101 are free to run without a license.

Set up a Project

After Wing is running, select New Project from the Project menu to create a new project. This dialog lets you choose or create the source directory and choose or create the Python environment you want to use for your new project. When creating a new source directory, you can optionally pull a revision control repository into it. Wing Pro can also create and install packages into new virtualenv, pipenv, Anaconda env, and Docker container environments.

See Project-Wide Properties and Per-File Properties for a description of all available properties.

Notice that Wing also offers other project types in the New Project dialog, including one for connecting to a remote host via SSH, running with Docker or other containers, accessing a Vagrant instance, working with Windows Subsystem for Linux, and a project type for each of the frameworks, tools, and libraries listed in How-Tos.

Wing may consume significant CPU time when it first analyzes your code base. Progress is indicated in the lower left of the IDE window. Once this is done, the results are cached across sessions and Wing should run with a snappy and responsive interface. See Source Code Analysis to learn how Wing’s source analysis system works.

Wing 101 does not have projects. Configuring the Python environment is instead done with Configure Python in the Edit menu.

Basic Configuration

You are now ready to start working with code, but may want to make a few configuration changes first:

There are many other options in Preferences.

Navigating Code

Wing Pro provides a number of different ways to navigate the structure of your code, and several methods for quickly finding symbols or files by name:

Source Index menus at the top of the editor provide quick access to other parts of a source file.

Goto-definition is available from the Source menu, and by right-clicking on symbols in the editor, Python Shell and Debug Console. Use the forward/back history buttons at the top left of the editor to return from the point of definition.

Find Points of Use in Wing Pro’s Source menu shows where the current symbol is being used. This distinguishes between separate but like-named symbols.

Find Symbol in the Source menu in Wing Pro and Wing Personal jumps to a symbol defined in the current file when you type a fragment of its name.

Find Symbol in Project in the Source menu in Wing Pro works the same way but searches all files in the project.

Open From Project in the File menu in Wing Pro and Wing Personal provides a similar interface for quickly opening project files.

See Navigating Source for details on the above.

Source Browser in the Tools menu in Wing Pro and Wing Personal provides module or class oriented display of the structure of your code. Details

Source Assistant in the Tools menu shows detailed information about symbols selected in the editor, auto-completer, Source Browser, Python Shell, Project, and other tools. Details

Searching

Wing Pro provides several different interfaces for searching your code. Which you use depends on what you want to search and how you prefer to interact with the search and replace functionality:

Toolbar search is a quick way to search the current file. Details

Search in the Tools menu shows the Search tool, which provides incremental text, wildcard, and regular expression search and replace in selections and the current file or documentation page. Details

Mini-search in Wing Pro and Wing Personal provides powerful keyboard-driven search and replace. The key bindings listed in the Mini-search area of the Edit menu display the search entry area at the bottom of the window. Details

Search in Files in the Tools menu in Wing Pro and Wing Personal shows the Search in Files tool, which provides wildcard and regular expression search and replace in filtered sets of files, directories, named file sets, and within the project and documentation. Details.

Editing Code

Wing Pro’s editor is designed to speed up the process of writing and modifying Python code, and to reduce the incidence of coding errors. Its features include:

Auto-completion in Wing’s editor, Python Shell and Debug Console speeds up typing and reduces coding errors. The auto-completer uses Tab by default for completion, but this can be changed in the Editor > Auto-completion > Completion Keys preference. This feature is disabled by default in Wing 101. Details

Читайте также:  Метронидазол и тержинан что лучше

Auto-indent in Wing Pro and Wing Personal matches the file’s existing indentation. When multiple lines are pasted, they are re-indented according to context. A single Undo reverts an unwanted indentation change. A selected range of code may be re-indented as a block using Indentation in the Source menu or the indentation toolbar group. The Indentation tool may be used to convert a whole file’s indentation style. Details

Auto-Editing in Wing Pro implements a range of operations such as auto-entering closing parentheses, brackets, braces, and quotes. Among other things, Wing also auto-enters invocation arguments, manages new blocks with the : key, and corrects out-of-order typing. Auto-editing operations can be enabled and disabled in the Editor > Auto-editing preferences group. The default set includes those operations that don’t affect finger memory. The others are well worth learning. Details

Refactoring operations in Wing Pro, accessed from the Refactoring menu, implement automated renaming and moving of symbols, creating functions or methods out of existing code, and introducing variables much more quickly than by manually editing code. Details

Multiple Selections can be made with Multiple Selections in the Edit menu, the multiple selections toolbar item, and by pressing Ctrl+Alt (or Command+Option on macOS) while making a selection with the mouse. Once multiple selections have been made, edits made will be applied to all the selections at once. Details

Code Warnings are shown in Wing Pro for syntax errors, indentation problems, unreachable code, use of undefined variables and attributes, unresolvable imports, and some other problems. External checkers like flake8, mypy, pep8, and pylint may also be configured as sources for the code warnings. Warnings are shown on the editor with details shown in a tooltip when the mouse hovers over the warning indicator. Warnings can be navigated from the warnings menu in the top right of the editor and managed from the Code Warnings tool. Details

Snippets in Wing Pro are included in Wing’s auto-completer as a quick way to enter commonly repeated patterns for coding standards, documentation, testing, and so forth. Data entry for snippet arguments is inline in the editor. Use the Tab key to move between the fields. Edit or add snippets in the Snippets tool. Details

Turbo Completion in Wing Pro is an optional auto-completion mode for Python, made possible by Wing’s powerful source analysis engine. When the Editor > Auto-completion > Python Turbo Mode preference is enabled, Wing turns every non-symbol key into a completion key in contexts where a new symbol name is not being typed. Details

Quick Selection operations in the Edit > Select menu allow selecting whole statements, blocks, or scopes before copying, editing, or searching through them. Details

Debugging Code

Wing’s debugger is a powerful tool for finding and fixing bugs, understanding unfamiliar code, and writing new code interactively. You can launch code from the Debug menu or toolbar, from the Python Shell, or from outside of the IDE either on the same machine or on another host. Wing also supports working with code running on containers like those provided by Docker.

Breakpoints can be set by clicking on the breakpoint margin to the left of the editor. Stepping operations are in the Debug menu and toolbar.

The Stack Data tool is used to inspect or change program data. Right-click on items to display the item as an array or in textual form. Hovering the mouse over a symbol in the editor shows the value for that symbol in a tooltip, if available on the active debug stack. Pressing Shift-Space shows tooltips for all symbols visible in the editor.

Debug process I/O is shown in the Debug I/O tool, or optionally in an external console.

Other debugger features include:

Interactive Debugging is supported by Wing Pro’s Debug Console, which provides a Python prompt that executes code in the current debug stack frame. When the debugger is paused, Wing also uses the live runtime state to populate the auto-completer in the editor, Source Assistant, goto-definition, and other tools. Details

Conditional Breakpoints can be used in Wing Pro to isolate and understand complex bugs by stopping before they occur. Using a conditional breakpoint to isolate a broken case and the Debug Console to design a fix is far more productive than relaunching code repeatedly. Details

Watching Values in Wing Pro by right-clicking on the editor or any of the data views tracks values over time by symbolic name or object reference in the Watch tool. Expressions can be also be watched. Details

Launch Configurations in the Project menu in Wing Pro and Wing Personal define different runtime environments for debugging, executing, and unit testing your code. Details.

Named Entry Points in the Debug menu in Wing Pro and Wing Personal provide a way to launch the same file with different debug environments. Details

Other Features

Wing Pro includes a number of other features designed to make Python coding easier and more productive:

Unit Testing in Wing Pro’s Testing tool works with unittest, doctest, pytest, nose, and Django unit tests. You can run tests suites, view the results, and debug tests. Details

Version Control in Wing Pro supports revision control with Mercurial, Git, Subversion, Perforce, Bazaar, and CVS. Wing auto-detects which systems are used in your project and shows the appropriate additional menus and tools in the Tools menu. Details.

Difference and Merge in the Source menu can be used to compare and merge files and directories on disk, files open in the IDE, an unsaved buffer with disk, and a working copy with its revision control repository. Details

Remote Development is easy in Wing Pro, to remote hosts, virtual machines, or containers that are accessible via SSH. In this model of remote development, Wing works seamlessly and securely with files stored entirely on the remote host. Use the Remote Hosts item in the Project menu to configure a remote host, then set the Python Executable in Project Properties to that remote host, and use Add Existing Directory in the Project menu to add your remote directories to the project. Wing can edit, debug, test, search, inspect, and manage files, run the Python Shell, and execute OS Commands on the remote host in the same way as it does when working locally. Details

Package management is available for virtualenv and pipenv, using the Packages tool in the Tools menu. This can be used to install, remove, and manage the packages that are installed into your project’s Python environment.

Containers like those provided by Docker are also supported. In this development model, files are stored locally but code is run inside a containerized environment. Details OS Commands in the Tools menu in Wing Pro and Wing Personal’s displays the OS Commands tool, which execute external tools for build, code generation, and other purposes. Details.

Preferences in the Edit menu (or WingPro menu on macOS) gives you control of the overall layout and color of the IDE, among many other options. Right click on tool and editor tabs for layout options, or drag tabs to move them or create new splits. Right-click on the toolbar to configure which tools are visible or to add your own. See Customization for details.

Читайте также:  Миокардиопатия что это такое симптомы и лечение у женщин

Perspectives in Wing Pro and Wing Personal let you save named tool panel layouts. Details.

Other Features like bookmarks, code folding, keyboard macros are also available, and you can extend Wing by writing Python scripts.

Further Reading

As you work with Wing Pro on your own software development projects, the following resources may be useful:

Thanks for using Wing Pro!

Источник

Wing Python IDE

The Intelligent Development Environment for Python

Navigation

Tutorial: Setting Python Path

However, in some cases code will depend on a different path provided either by setting the environment variable PYTHONPATH before starting Python, or by modifying sys.path at runtime before importing modules.

The configuration used here is for illustrative purposes only. You could run the example code without altering the Python Path by moving the path_example.py file to the same location as the example scripts.

Startup Environment

Wing uses its startup environment as the default environment for your Python code. As a result, if PYTHONPATH is set when you start Wing, it will also be used with your code. If this inherited path matches the needs of your code, then you don’t need to set Python Path in Wing. However, if you have different Python environments on your system or code with different path expectations, then you should set Python Path in the project so that switching projects will also switch to the correct environment.

Virtualenv and Anaconda Environments

You can also create a new virtualenv or Anaconda environment at the same time as creating a Wing project by selecting the Create New Virtualenv or Create New Anaconda Environment project types in the New Project dialog, accessed from the Project menu.

But don’t do this now; you’ll need the current project as you work through this tutorial.

Источник

2.1. Начало работы в Python 3 и Wing IDE 101¶

2.1.1. О версиях Python¶

Сейчас существуют две основных ветки (версии) развития языка Python (питон): Python 2 и Python 3. Версия 2 официально считается устаревшей (поддержка версии 2 заканчивается в 2020 году), версия 3 — более новой и современной. Мы будем изучать именно версию 3. Версия 2 существенно отличается от версии 3, мы не будем обсуждать эти отличия.

В пределах как версии 2, так и версии 3 есть «подверсии», например, последняя версия из третьей ветки сейчас (2020 г.) — версия 3.8.2 (не считая тех версий, которые находятся еще в разработке). В принципе, для наших занятий можно использовать более-менее любую версию питона из третьей ветки, лучше как минимум 3.3, но если нет особенных причин, то устанавливайте последнюю доступную вам версию.

2.1.2. Установка Python¶

Python — это свободное кросс-платформенное программное обеспечение, поэтому его можно легко скачать с официального сайта, можно свободно распространять, и можно установить на все современные операционные системы.

Если вы работаете в другой операционной системе, то разберитесь, как установить питон, самостоятельно. В Linux, например, питон есть в репозиториях всех ведущих дистрибутивов, пакет обычно называется python3 (а просто python — это питон второй версии).

2.1.3. Установка Wing IDE¶

Сам по себе питон — это только интерпретатор кода. Он запускает ваши программы, но не содержит удобного редактора. Поэтому для написания программ я советую вам использовать среду разработки (по сути, продвинутый редактор) Wing IDE.

Wing IDE — это, к сожалению, не свободное ПО, но у него существует официально бесплатная версия для образовательных целей, называется Wing IDE 101. Она доступна как для Windows, так и для Linux и macOS.

Все программы для установки можно скачать с официального сайта Wing IDE (http://wingware.com/, через пункт Download — Wing IDE 101); установщик под Windows также можно скачать со странички курса. Обратите внимание, что вам нужна именно версия 101, а не какая-нибудь другая! Установите Wing IDE с помощью этого установщика, ничего сложного в нем нет.

Wing IDE — это просто среда разработки (IDE) для Python, т.е. удобный редактор программ, позволяющий легко запускать программы с помощью питона (именно поэтому надо отдельно устанавливать сам Python — Wing IDE его не включает в себя). В принципе, вы можете использовать и какую-нибудь другую среду разработки, но тогда разбирайтесь с ней сами. В частности, сам Python включает простенькую среду разработки Python IDLE, ее описание вы можете встретить во многих книжках по Python, но она слишком простая и потому не очень удобная. Так же есть популярная среда PyCharm, но на мой вкус она слишком сложная.

2.1.4. Проверка установки¶

Запустите Wing IDE. Появится следующее окошко:

Если у вас не получается, напишите мне [1], указав, куда вы установили питон, и прислав скриншоты основного окна Wing IDE и диалога Edit — Configure Python.

2.1.5. Первая программа¶

В основном меню Wing IDE выберите пункт File — New. Появится окно для редактирования текста программы. В этом окне наберите следующий текст:

(Здесь » — это символ кавычек.)

Должно получиться так:

Убедитесь, что опечаток нет. Сохраните программу: нажмите Ctrl-S или выберите пункт меню File — Save As. Wing IDE предложит выбрать имя файла для сохранения, для первой программы можно выбрать любое имя.

Обратите внимание, что Wing IDE раскрашивает вашу программу. Это делается для того, чтобы ее было удобнее читать; на самом деле для питона цвет не важен, он сделан только для того, чтобы вам было удобнее читать. Аналогично, в этом тексте код тоже раскрашен, причем раскраска может быть немного другой (это просто обусловлено системой, которую я использую для написания текста). Но еще раз: цвета только для удобства чтения, никакой больше нагрузки они не несут, в частности, Wing может раскрашивать не так, как вы видите в этом тексте, это не страшно.

После этого запустите программу, нажав на кнопку с зеленым треугольничком—стрелочкой на панели инструментов над текстом программы. Результат выполнения программы появляется в правой нижней части экрана, в панели «Python Shell» А именно, там вы можете увидеть один из двух возможных результатов, показанных на двух рисунках ниже.

Если там появилась надпись «Test 4»:

значит, все хорошо, программа успешно выполнилась.

Если же там появился длинный текст со словами «Traceback» (в начале) и «Error» (в конце):

значит, в вашей программе есть ошибки. Подробнее про ошибки ниже (раздел Ошибки в программе ), а пока, если вы увидели ошибку, то просто внимательно проверьте, не ошиблись ли вы где-нибудь в наборе программы.

Позапускайте программу (зеленой стрелочкой) ещё несколько раз и посмотрите на результаты. Вы увидите что, Wing IDE каждый раз печатает строку evaluate. перед запуском программы, потом программа печатает свою строку. Вывод программы перемешивается с выводом Wing IDE — ничего страшного, это нормально.

Можно также запускать программу нажатием на кнопку с картинкой типа красного жучка. Это немного другой режим запуска, более удобный для поиска ошибок. Попробуйте позапускать и так, и так, посмотрите на отличия (основное отличие пока — при запуске через «красного жучка» вывод предыдущих программ затирается).

2.1.6. Ошибки в программе¶

В вашей программе могут быть серьёзные ошибки — такие, что питон «не понимает», что вы от него хотите (а могут быть и не столь серьёзные — программа отработает как бы нормально, но выдаст неверный результат). В случае таких серьезных ошибок питон выдаст сообщение, похожее на сообщение, показанное на рисунке выше. Оно обычно начинается со слова Traceback, а ближе к концу в нем есть слово Error.

Читайте также:  багажник на крышу автомобиля хонда срв

С ошибками удобнее разбираться, запуская программу в режиме «красного жучка». В таком случае Wing IDE подсвечивает строку около ошибки красным, а подробную информацию пишет в особом окошке справа.

А пока посмотрите внимательно на строчку с ошибкой (при запуске через жучка питон подсвечивает ее красным, при запуске через стрелочку — только пишет номер строки), и на строчки рядом — и попробуйте понять, что там не так. В примере на рисунке я забыл вторую цифру 2 (в результате чего питону стало непонятно, на что надо умножать). (В примере на рисунке я запускал программу через зеленую стрелочку, а не через «красного жучка», поэтому там нет подсвеченной красным строки.)

Имейте в виду, что питон не телепат и не может точно определить, где вы допустили ошибку. Он подсвечивает красным ту строку, где текст программы впервые разошёлся с правилами языка. Поэтому бывает, что на самом деле ваша ошибка чуть выше, чем подсвеченная строка (а иногда — и намного выше). Но тем не менее место, которое выделил питон, обычно бывает полезно при поиске ошибки.

Попробуйте в своей программе поделать разные ошибки и посмотрите, как на них отреагирует питон.

2.1.7. Как работает эта программа¶

Давайте разберём, как эта программа работает. Напомню её текст:

Вообще, любая программа — это, в первую очередь, последовательность команд, которые программист даёт компьютеру, а компьютер будет последовательно их выполнять.

Команда print разделяет выводимые элементы пробелами, поэтому между Test и 4 выведен пробел.

2.1.8. Использование питона как калькулятора¶

В выражениях можно использовать следующие операторы:

Кроме того, есть так называемые функции:

В одной программе можно вычислять несколько выражений. Например, программа

вычисляет три выражения. Первая команда print выводит на экран две четвёрки, разделённых пробелом. Вторая команда просто выводит одно число 9. Оно будет выведено на отдельной строке, т.к. каждая команда print выводит одну строку. Обратите еще раз внимание, что аргументы команды разделяются запятыми.

Можно также, как мы видели раньше, смешивать текст (в кавычках) и выражения:

2.1.9. Простейший ввод и вывод. Переменные¶

Но не очень интересно писать программы, которые всегда выводят одно и то же. Хочется, чтобы программа что-нибудь запрашивала у пользователя, и работала с учётом того, что пользователь ввёл. Давайте, например, напишем программу, которая будет спрашивать у пользователя два числа и выводить на экран их сумму.

Но для этого нам придётся научиться ещё одной важной вещи. Когда пользователь вводит два числа, программе надо их как-то запомнить, чтобы потом сложить между собой и результат вывести на экран. Для этого у компьютера есть память (оперативная память). Программа может использовать эту память и положить туда числа, введённые пользователем. А потом посмотреть, что там лежит, сложить эти два числа, и вывести на экран.

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

Если вы запустите программу «красным жучком», то все будет аналогично, только текст вам надо будет вводить в пустом окошке «Debug I/O», которое появится на месте окошка «Python Shell».

Теперь разберем, как эта программа работает.

В программе можно заводить несколько переменных. Простейший вариант может выглядеть так:

Эта программа считывает две строки, которые вводит пользователь, и выводит их, причем сначала вторую, а потом первую.

Но мы хотели написать программу, которая выводит сумму двух чисел. Простой подход тут не сработает:

сделает вовсе не то, что вы могли ожидать: питон пока считает, что в a и b могут лежать какие угодно строки, и не понимает, что вы имели в виду числа.

Чтобы объяснить, что вы имеете в виду числа, надо написать так:

Запустите эту программу. В окошке ввода наберите какое-нибудь число, нажмите Enter, наберите второе число и еще раз нажмите Enter. Вы увидете, что программа вывела их сумму.

Чтобы вводить числа через пробел, надо использовать другую конструкцию:

Это пока магия, ее придется запомнить наизусть. Потом вы поймете, что здесь что значит. Обратите внимание, что после слова int тут нет скобок, а вот после input и split есть.

Так можно вводить сколько угодно чисел; например, чтобы считать четыре числа, вводимые в одной строке, надо написать

2.1.10. Присваивания¶

Пока мы умеем записывать в переменные только то, что пользователь ввел с клавиатуры. На самом деле, намного чаще приходится записывать в переменные значения, которые программа сама вычисляет. Для этого есть специальная команда, которая называется присваивание (и на самом деле мы ее уже видели):

обозначает «в переменную a записать 10».

Если в переменной уже было что-то записано, то после присваивания старое значение затирается:

в результате в a лежит 30, а про 20 все забыли.

Особый интересный вариант — справа можно упоминать ту же переменную, которая стоит слева — тогда будет использоваться ее предыдущее значение:

обозначает «в a записать 10, а в b — 20».

Запись a = 10 читается «переменной a присвоить 10», или кратко « a присвоить 10». Не надо говорить « a равно 10», т.к. «равно» — это не глагол, и не понятно, какое действие совершается. Более того, если запись a = a + 1 прочитать с «равно», то получается « a равно a плюс один», что никак не похоже на команду, а скорее на уравнение, которое не имеет решений. Поэтому говорите «присвоить», а не «равно».

2.1.11. Комментарии¶

(Эта информация вам прямо сейчас не нужна, но будет полезна при чтении дальнейших разделов.)

В программе можно оставлять так называемые комментарии. А именно, если где-то в программе встречается символ «решетка» ( # ), то этот символ и все, что идет за ним до конца строки, полностью игнорируется питоном. Таким образом можно в программе оставлять пометки для себя, или для других программистов, которые будут читать вашу программу. Например

Здесь запись # считали число полностью игнорируется питоном, как будто этих символов нет вообще, а запись a = int(input()) работает как и должна.

В частности, решетка может стоять в начале строки, тогда вся эта строка будет игнорироваться:

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

2.1.12. Язык программирования как конструктор¶

Выше я рассказал ряд самых основных конструкций языка питон. Теперь ваша задача будет из этих конструкций, как из конструктора, собирать программы. Относитесь к этому именно как к конструктору: все программирование — это сборка больших программ из таких отдельных команд.

2.1.13. Примеры решения задач¶

Приведу несколько примеров задач, аналогичных тем, которые встречаются на олимпиадах и в моем курсе.

Вася купил \(N\) булочек, а Маша — на \(K\) булочек больше. Сколько всего булочек купили ребята?

Входные данные: Выведите одно число — ответ на задачу.

Источник

Познавательно-развлекательный портал