Python запуск скрипта pycharm

Python запуск скрипта pycharm

В прошлой теме было описано создание простейшего скрипта на языке Python. Для создания скрипта использовался текстовый редактор. В моем случае это был Notepad++. Но есть и другой способ создания программ, который представляет использование различных интегрированных сред разработки или IDE.

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

Для Python можно использовать различные среды разработки, но одной из самых популярных из них является среда PyCharm , созданная компанией JetBrains. Эта среда динамично развивается, постоянно обновляется и доступна для наиболее распространенных операционных систем — Windows, MacOS, Linux.

Правда, она имеет одно важное ограничение. А именно она доступна в двух основных вариантах: платный выпуск Professional и бесплатный Community. Многие базовые возможности доступны и в бесплатном выпуске Community. В то же время ряд возможностей, например, веб-разработка, доступны только в платном Professional.

В нашем случае воспользуемся бесплатным выпуском Community. Для этого перейдем на страницу загрузки и загрузим установочный файл PyCharm Community.

IDE PyCharm

После загрузки выполним его установку.

Установка PyCharm

После завершения установки запустим программу. При первом запуске открывается начальное окно:

Первая программа в PyCharm

Создадим проект и для этого выберем пункт New Project .

Далее нам откроется окно для настройки проекта. В поле Location необходимо указать путь к проекту. В моем случае проект будет помещаться в папку HelloApp. Собственно название папки и будет названием проекта.

Настройка проекта в PyCharm

Кроме пути к проекту все остальные настройки оставим по умолчанию и нажмем на кнопку Create для создания проекта.

После этого будет создан пустой проект:

Первый проект в PyCharm

В центре среды будет открыт файл main.py с некоторым содержимым по умолчанию.

Теперь создадим простейшую программу. Для этого изменим код файла main.py следующим образом:

name = input("Введите ваше имя: ") print("Привет,", name)

Для запуска скрипта нажмем на зеленую стрелку в панели инструментов программы:

Запуск программы в PyCharm

Также для запуска можно перейти в меню Run и там нажать на подпункт Run ‘main’ )

После этого внизу IDE отобразится окно вывода, где надо будет ввести имя и где после этого будет выведено приветствие:

Источник

Create and run your first project

To get started with PyCharm, let’s write a Python script.

Create a Python project

Create a new project

  1. If you’re on the Welcome screen, click New Project . If you’ve already got any project open, choose File | New Project from the main menu.
  2. Although you can create projects of various types in PyCharm, in this tutorial let’s create a simple Pure Python project. This template will create an empty project.
  3. Choose the project location. Click button next to the Location field and specify the directory for your project.
  4. Also, deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.
  5. Python best practice is to create a virtualenv for each project. In most cases, PyCharm create a new virtual environment automatically and you don’t need to configure anything. Still, you can preview and modify the venv options. Expand the Python Interpreter: New Virtualenv Environment node and select a tool used to create a new virtual environment. Let’s choose Virtualenv tool, and specify the location of the environment and the base Python interpreter used for the new virtual environment. If PyCharm detects no Python on your machine, it provides the following options:
    • Specify a path to the Python executable (in case of non-standard installation)
    • Download and install the latest Python versions from python.org
    • Install Python using the Command-Line Developer Tools (macOS only).

Downloading Python when creating a new project

Downloading Python when creating a new project

Now click the Create button at the bottom of the New Project dialog.

If you’ve already got a project open, after clicking Create PyCharm will ask you whether to open a new project in the current window or in a new one. Choose Open in current window — this will close the current project, but you’ll be able to reopen it later. See the page Open, reopen, and close projects for details.

Create a Python file

  1. In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New . . Create a Python file
  2. Select the option Python File from the context menu, and then type the new filename. Creating a new Python filePyCharm creates a new Python file and opens it for editing. New Python file

Edit Python code

Let’s start editing the Python file you’ve just created.

  1. Start with declaring a class. Immediately as you start typing, PyCharm suggests how to complete your line: Create class completionChoose the keyword class and type the class name, Car .
  2. PyCharm informs you about the missing colon, then expected indentation: Create class analysisNote that PyCharm analyses your code on-the-fly, the results are immediately shown in the inspection indicator in the upper-right corner of the editor. This inspection indication works like a traffic light: when it is green, everything is OK, and you can go on with your code; a yellow light means some minor problems that however will not affect compilation; but when the light is red, it means that you have some serious errors. Click it to preview the details in the Problems tool window. View code problems
  3. Let’s continue creating the function __init__ : when you just type the opening brace, PyCharm creates the entire code construct (mandatory parameter self , closing brace and colon), and provides proper indentation. Create class
  4. If you notice any inspection warnings as you’re editing your code, click the bulb symbol to preview the list of possible fixes and recommended actions: Intention actions
  5. Let’s copy and paste the entire code sample. Hover the mouse cursor over the upper-right corner of the code block below, click the copy icon, and then paste the code into the PyCharm editor replacing the content of the Car.py file: This application is intended for Python 3

At this point, you’re ready to run your first Python application in PyCharm.

Run your application

Use either of the following ways to run your code:

  • Right-click the editor and select Run ‘Car’ from the context menu .
  • Press Control+Shift+F10 .
  • Since this Python script contains a main function, you can click an icon in the gutter. If you hover your mouse pointer over it, the available commands show up: Running a scriptIf you click this icon, you’ll see the popup menu of the available commands. Choose Run ‘Car’ : Run command

PyCharm executes your code in the Run tool window.

Run Tool window

Here you can enter the expected values and preview the script output.

Note that PyCharm has created a temporary run/debug configuration for the Car file.

Temporary run/debug configuration

The run/debug configuration defines the way PyCharm executes your code. You can save it to make it a permanent configuration or modify its parameters. See Run/debug configurations for more details about running Python code.

Summary

Congratulations on completing your first script in PyCharm! Let’s repeat what you’ve done with the help of PyCharm:

  • Created a project.
  • Created a file in the project.
  • Created the source code.
  • Ran this source code.

Источник

Python console

Python console enables executing Python commands and scripts line by line, similar to your experience with Python Shell.

Actions available in the Python Console

  • Type commands and press Enter to execute them. Results are displayed in the same console.
  • Use basic code completion Control+Space and tab completion.
  • Use the await keyword to run asyncio coroutines.
  • Use Up and Down arrow keys to scroll through the history of commands, and execute the required ones.
  • Load source code from the editor into console.
  • Use the context menu to copy the contents of the console to the clipboard, compare it with the clipboard, or clear the console.
  • Use the toolbar buttons to control your session in the console.
  • Configure color scheme of the console to meet your preferences. Refer to the section Configure color schemes for consoles for details.

Working with Python console

The console appears as a tool window every time you choose the corresponding command on the Tools menu. You can assign a shortcut to open Python console: press Control+Alt+S , navigate to Keymap , specify a shortcut for Main menu | Tools | Python or Debug Console .

The main reason for using the Python console within PyCharm is to benefit from the main IDE features, such as code completion, code analysis, and quick fixes.

Code completion in the Python console

You can use up and down arrow keys to browse through the history of executed commands, and repeat the desired ones. To preview the variable values calculated in the course of the execution, click and check the Special Variables list.

Show variables in the Python console

The console is available for all types of Python interpreters and virtual environments, both local and remote.

Preview a variable as an array

When your variables are numpy arrays or dataframes, you can preview them as an array in a separate window. To try it, do one of the following:

  • Click the link View as Array / View as DataFrame : Viewing variables in array when running from Python console
  • From the context menu of a variable, choose View as Array / View as DataFrame : Viewing variables in data frames when running from Python console

The variable will be opened in the Data tab of the SciView window.

View an array or dataframe in a separate window

Run source code from the editor in console

  1. Open file in the editor, and select a fragment of code to be executed.
  2. From the context menu of the selection, choose Execute Selection in Python Console , or press Alt+Shift+E : Context menu for executing the code selectionWith no selection, the command changes to Execute line in console . Choose this command from the context menu, or press Alt+Shift+E . The line at caret loads into the Python console, and runs.
  3. Watch the code selection execution: Execution of the code selection in the console

By default, the Python console executes Python commands using the Python interpreter defined for the project. However, you can assign an alternative Python interpreter.

Run asyncio coroutines

  1. In the editor, select a fragment of code which contains the definition of an asyncio coroutine.
  2. From the context menu, select Execute Selection in Python Console , or press Alt+Shift+E : Selecting and executing asyncio coroutines in the Python console
  3. After the code is executed on the Python console, run the coroutine by using the await keyword: Execution of the asyncio coroutine in the console

Configure Python console settings

Search an alternative Python interpreter

  1. In the Settings dialog ( Control+Alt+S ), select Build, Execution, Deployment | Console | Python Console .
  2. Select any available interpreter from the Python interpreter list. Note that you cannot introduce a new interpreter here. If you want to come up with the new interpreter, you need to create it first.
  3. In needed, click the Configure Interpreters link to inspect the list of the installed packages and add new ones. Mind the code in the Starting script area. It contains the script that will be executed after you open the Python console. Use it to pre-code some required Python commands.

When working on several Python scripts, you might want to execute each in a separate Python console.

Run several Python consoles

Rename the Python console

  1. Click to add a new Python console.
  2. By default, each console has the name Python Console with an index. To make a console reflect the script you’re running, right-click the console tab, select Rename Console , and enter any meaningful name.

All the commands you’re running in the Python console are executed one by one. If the commands require substantial time to get executed, you might want to preview and manage the execution queue.

Manage the command execution queue

Console command queue

  1. Go to Settings | Build, Execution, Deployment | Console and enable the Command queue for Python Console checkbox.
  2. Click on the console toolbar to open the queue.
  3. In the Python Console Command Queue dialog, review the list of commands. If needed, click to delete the command from the queue.

Note, once the command is executed, it disappears from the queue. To preview all previously executed commands browse the console history ().

Источник

Читайте также:  Unique page title - My Site
Оцените статью