How to run python in windows terminal

Как запустить скрипт Python

Какой бы язык программирования вы не начали изучать, вашей первой программой, скорее всего, будет «Hello World!».

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

Что такое оболочка?

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

Что бы мы ни делали на компьютере — от анализа данных в Excel до игр — все облегчается операционной системой.

Программы операционной системы делятся на два вида: программы оболочки и ядра.

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

Оболочка также называется командным процессором.

Что такое терминал?

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

Чтобы открыть терминал в Windows, нажмите клавиши Windows + R , затем наберите cmd и нажмите Enter. В Linux терминал открывается сочетанием клавиш Ctrl + Alt + T .

Что такое оболочка Python?

Python — это интерпретируемый язык программирования. Это значит, что интерпретатор Python читает строку кода, выполняет эту строку, а затем, если на этом шаге нет ошибок, процесс повторяется.

Оболочка Python дает вам интерфейс командной строки. С его помощью можно интерактивно передавать команды непосредственно в интерпретатор Python.

Подробнее об оболочке Python можно почитать в документации.

От редакции Pythonist. Об интерпретаторах Python можно почитать в статье «Топ-7 бесплатных компиляторов и интерпретаторов Python».

Как пользоваться оболочкой Python?

Чтобы запустить оболочку Python, просто введите python в терминале и нажмите Enter.

C:\Users\Suchandra Datta>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>print("hello world!")

Интерактивная оболочка еще называется REPL (read-evaluate-print loop — «цикл „чтение — вычисление — вывод“». Она читает команду, оценивает и выполняет ее, выводит результат (если он есть) и повторяет этот процесс, пока вы не выйдете из оболочки.

Читайте также:  Decode html entities to text

Выйти из оболочки можно по-разному:

  • нажать Ctrl+Z в Windows или Ctrl+D в Unix-подобных системах
  • выполнить команду exit()
  • выполнить команду quit()
C:\Users\Suchandra Datta>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print("HELLO WORLD") HELLO WORLD >>> quit() C:\Users\Suchandra Datta>
C:\Users\Suchandra Datta>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exit() C:\Users\Suchandra Datta>
C:\Users\Suchandra Datta>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z C:\Users\Suchandra Datta>

Что можно делать в оболочке Python?

В оболочке можно делать практически все, что вообще позволяет делать язык Python: использовать переменные, циклы, условия для определения функций и т. д.

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

Давайте рассмотрим пример:

>>> >>> watch_list = ["stranger_things_s1", "stranger_things_s2", "stranger_things_s3","stranger_things_s4"] >>> >>>

Здесь мы определили список сериалов прямо в оболочке Python.

Теперь давайте определим функцию. Она будет принимать наш список сериалов и возвращать один из них случайным образом.

>>> def weekend_party(show_list): . r = random.randint(0, len(show_list)-1) . return show_list[r] .

Обратите внимание на троеточия в начале строк.

Наконец, чтобы запустить функцию в оболочке, мы просто вызываем ее так же, как делали бы это в скрипте:

>>> weekend_party(watch_list) 'stranger_things_s1' >>> >>> >>> weekend_party(watch_list) 'stranger_things_s3' >>> >>> >>> weekend_party(watch_list) 'stranger_things_s2' >>> >>> >>> weekend_party(watch_list) 'stranger_things_s2' >>> >>> >>> weekend_party(watch_list) 'stranger_things_s3' >>>

В оболочке можно просматривать модули Python:

>>> >>> >>> import numpy >>> numpy.__version__ '1.20.1' >>>

Посмотреть, какие методы и атрибуты предлагает модуль, можно при помощи метода dir() :

>>> >>> x = dir(numpy) >>> len(x) 606 >>> x[0:3] ['ALLOW_THREADS', 'AxisError', 'BUFSIZE']

Мы видим, что всего Numpy имеет 606 методов и свойств.

Как запустить скрипт Python

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

Но по-настоящему большие и сложные программы пишутся в редакторе кода. Они сохраняются в отдельных файлах с расширением .py. Их называют скриптами (сценариями) Python. Эти программы можно запускать на выполнение в терминале. Для этого используется команда Python.

Стандартный синтаксис следующий:

Все команды, которые мы выполняли в оболочке, можно записать в скрипт и запустить в терминале.

Заключение

Итак, вы познакомились с понятиями оболочки и терминала, а также научились пользоваться оболочкой Python. Мы также разобрали, как запустить скрипт Python в командной строке.

Читайте также:  Oracle java and android

Источник

How to run the python shell inside a terminal in Windows?

I’ve scrolled the internet all over and theres no simple, clean explanation for this. How can I open the Python shell, but inside a terminal window such as CMD? I have an application for it, but want to run it inside a terminal, so I can practice Python code inside my IDE like VS code.

so I can practice Python code inside my IDE like VS code , in fact, VS just do same thing as open cmd, and type python in cmd, give your a REPL to run your input

2 Answers 2

If you have a reasonably new version of Python you need to run py.exe (or just py ) instead of python.exe , because the real python executable ( python.exe ) is not in your path environment variable by default, whereas py.exe is in the /windows directory and thus automatically in path.

So to run your script type py yourscript.py from the directory of your script. If you just run py it will start the interactive interpreter.

Under the title Start a Python script (almost at the beginning) there is an instruction. Just write from the command prompt:

As in each command, press Enter and your script will be executed.

Of course, I assume that you have installed Python on your computer. If this is not the case, start from installing it.

I have quite a new Python version installed (3.6.5) and start Python writing just python. Writing just py also does the job, but (IMHO) it is not necessary.

If you want to start Python interpreter and play around with some Python commands, write just python and Enter. The interpreter will start and display its own command prompt (>>>).

Источник

How To Open Python on Windows, Mac, Linux

How to open Python

You’ll now learn how to open Python on Linux, Windows, and MacOS. First of all, you should know that there are two ways of using Python:

  1. Start an interactive shell, also called a REPL, short for read-evaluate-print-loop.
  2. Start a Python program that you stored in one or more files with the .py extension.

In this tutorial, we’ll start with the interactive shell because it’s ideal for exploring the language. But at some point, using the REPL won’t cut it anymore and you’ll have to start creating Python files.

If you installed Python on your local machine, you first need to start a terminal or command prompt before you can start the Python interactive shell. On all platforms, you should be able to start Python 3 with the command python3 (or sometimes just python ). Just be sure you are running Python 3, not 2, because some systems can have both versions installed.

Читайте также:  Королевский питон домашний питомец

How to open Python on Windows

On Windows, you can start Python from a terminal. E.g., to start PowerShell simply hit the Windows key and start typing “PowerShell”. You can use the ‘Command Prompt’ program if you don’t have PowerShell. When in a shell or command prompt, enter one of the following commands (try them in the given order):

The first command ( py ) is a wrapper script that allows you to start the latest version of Python. If it works, great. Just remember that I’ll often refer to python or python3 in the tutorial. You will need to use py in those cases.

Python started from Windows PowerShell

How to open Python on Mac

On MacOS, search for a program called terminal. You can do so by pressing the command key (⌘) + space bar. This will open up the Spotlight search bar, in which you start typing the word ‘terminal’.

Once you started the terminal, enter python3 to open the Python REPL. If that doesn’t work, try entering python instead (without the 3).

How to open Python on Linux

On Linux, you first need to start a terminal. This can often be done with the shortcut ctrl + alt + T . Alternatively, you can search for the terminal program in your start menu. The name and where to find it differ from distribution to distribution. Once you have a terminal running, enter python3 to start the Python REPL. If that doesn’t work, try python instead (without the 3).

How to close the REPL

Now that you know how to open the REPL, it would be nice to properly close it too. If you simply close the terminal window, you will be able to close the REPL as well. However, it won’t be a clean exit and your terminal will usually warn you about that too. So how do you exit the REPL cleanly?

What works on every OS, is the following command: exit()

If you’re on Linux or MacOS, you can also use a little trick. By pressing control + d, the REPL will exit immediately. Control + d sends the ‘end of file’ character the to terminal, and the REPL interprets this as a request to exit Python. On Windows, you can do something similar by pressing control + z and then hitting enter.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Источник

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