- How to Run a Python Script in Windows
- Your First Python Script
- Run Python Code from the Command Prompt
- Run Python Code from an IDE
- Run a Python Script from the File Manager
- Running Python Scripts in Windows: Next Steps
- Запуск Python и python-скрипт на компьютере
- Где запускать Python-скрипты и как?
- Запуск Python-кода интерактивно
- Интерактивный режим в Linux
- Интерактивный режим в macOS
- Интерактивный режим в Windows
- Запуск Python-скриптов в интерактивном режиме
- Как выполняются Python-скрипты?
- Блок-схема выполнения кода интерпретатором
- Как запускать Python-скрипты?
- Как запускать скрипт в командной строке?
- How to Run Python Scripts on Windows
- Install Python on Windows
- Step 1: Download Python Installer
- Step 2: Execute Python Installer
- Step 3: Install Python
- Create Python Script on Windows
- Step 1: Create Simple Text File
- Step 2: Change File Extension to “.py”
- Step 3: Open File
- Step 4: Add Python Code
- Run Python Scripts on Windows
- Step 1: Open Command Prompt
- Step 2: Move to Python Script Directory
- Step 3: Run Python Script
- Conclusion
- About the author
- Rafia Zafar
How to Run a Python Script in Windows
When it comes to operating systems, there are three main ones for personal computers: Microsoft Windows, Apple’s macOS, and Linux. You can use any of these operating systems to develop and run your Python programs. However, there are subtle differences you need to keep in mind while developing your projects. In this article, we’ll outline how to run a Python script in Windows.
In general, we recommend you work with Python 3, which is the latest version. If you need some help getting Python installed, check out our article How to Install Python on Windows. To make sure you’re up to speed with the terminology we use in this article, take a look at Python Terms Beginners Should Know – Part 1.
If you’re new to programming, a good place to start is our Python Basics track, which contains three useful courses to teach you the fundamentals. We have more course suggestions in the article How to Learn Python Online for Free.
Your First Python Script
To follow along with this article, you’ll need to create your own Python script. This script doesn’t have to be fancy – a ‘Hello, World!’ program will do. Simply open a text editor (such as Notepad) and type:
Just make sure there aren’t any spaces before the print() statement. Then save it as ‘script.py’.
Run Python Code from the Command Prompt
The first way to work with Python in Windows is through an interactive session. To get an interactive session started, just open the Command Prompt. Search for cmd on the toolbar, then hit Enter. Once the command prompt is open, simply type python and hit Enter again.
When you’re in an interactive session, every Python statement is executed immediately and any output is displayed directly beneath. Try typing:
>>> print('Hello, World!') Hello, World!
From here, you can write any Python code you want. To exit the interactive session, type quit() or exit() .
To run the script that we created above, you can call the Python program from the Command Prompt and tell it which file to execute. From the Command Prompt, simply type:
You’ll see the Hello, World! output printed directly to the screen. For more details on this method, check out How to Open and Run Python Files in the Terminal.
This is the most basic method of executing scripts that you should be familiar with. You could develop your whole project in Notepad and run the script in this way. This is totally legit, but for many applications it’s not the easiest method.
Run Python Code from an IDE
A much more useful way to develop and run your Python projects is using an Integrated Development Environment (IDE). For some background reading, check out our article 4 Best Python IDE and Code Editors. My personal recommendation is to use Spyder (which has a nice mix of features and is user-friendly) but any IDE will do. You can download Spyder here.
Once you’ve downloaded and installed it, open Spyder to get started. Since you already have your script written, you just need to open it in the editor. To run the script, simply click the play button in the top toolbar. You should see the output displayed in the interactive console.
Using an IDE to develop and run your Python projects is the most convenient way to work.
Run a Python Script from the File Manager
The final way of running your Python script that we’ll discuss is double-clicking the .py file. This is possibly the least useful option, but it could be convenient once you have fully developed and tested your project. It could also require a little bit of configuration.
You need to ensure your .py file is associated with python.exe. Right click the .py file, select Open with > Python. Now try double-clicking the .py file. You’ll see the Command Prompt flash briefly, then close again. To avoid this, you can add the following line to the end of your script:
input('Press Enter to Continue')
Now the script will stop when you hit the Enter key.
Running Python Scripts in Windows: Next Steps
In this article, we discussed three ways to run your Python scripts in Windows. This is something you’ll need to do often to develop and test your programs.
Learning anything new can be challenging. For some tips on the best ways to learn Python, check out our article 5 Tips for Learning Python from Scratch. With a little bit of consistent effort, you’ll become a Python master in no time!
Запуск Python и python-скрипт на компьютере
Код, написанный на языке Python, может храниться в редакторе кода, IDE или файле. И он не будет работать, если не знать, как его правильно запускать.
В этом материале рассмотрим 7 способов запуска кода, написанного на Python. Они будут работать вне зависимости от операционной системы, среды Python или местоположения кода.
Где запускать Python-скрипты и как?
Python-код можно запустить одним из следующих способов:
- С помощью командной строки операционной системы (shell или терминал);
- С помощью конкретной версии Python или Anaconda;
- Использовать Crontab;
- Запустить код с помощью другого Python-скрипта;
- С помощью файлового менеджера;
- Использовать интерактивный режим Python;
- Использовать IDE или редактор кода.
Запуск Python-кода интерактивно
Для запуска интерактивной сессии нужно просто открыть терминал или командную строку и ввести python (или python3 в зависимости от версии). После нажатия Enter запустится интерактивный режим.
Вот как запустить интерактивный режим в разных ОС.
Интерактивный режим в Linux
Откройте терминал. Он должен выглядеть приблизительно вот так :
После нажатия Enter будет запущен интерактивный режим Python.
Интерактивный режим в macOS
На устройствах с macOS все работает похожим образом. Изображение ниже демонстрирует интерактивный режим в этой ОС.
Интерактивный режим в Windows
В Windows нужно открыть командную строку и ввести python . После нажатия Enter появится приблизительно следующее:
Запуск Python-скриптов в интерактивном режиме
В таком режиме можно писать код и исполнять его, чтобы получить желаемый результат или отчет об ошибке. Возьмем в качестве примера следующий цикл.
Этот код должен выводить целые числа от 0 до 5. В данном случае вывод — все, что появилось после print(i) .
Для выхода из интерактивного режима нужно написать следующее:
И нажать Enter. Вы вернетесь в терминал, из которого и начинали.
Есть и другие способы остановки работы с интерактивным режимом Python. В Linux нужно нажать Ctrl + D, а в Windows — Ctrl + Z + Enter.
Стоит отметить, что при использовании этого режима Python-скрипты не сохраняются в локальный файл.
Как выполняются Python-скрипты?
Отличный способ представить, что происходит при выполнении Python-скрипта, — использовать диаграмму ниже. Этот блок представляет собой скрипт (или функцию) Python, а каждый внутренний блок — строка кода.
Первая строка (кода): Вторая = строка кода Третья строка > кода: Четвертая (строка == кода) Пятая строка кода
При запуске скрипта интерпретатор Python проходит сверху вниз, выполняя каждую из них. Именно таким образом происходит выполнение кода.
Блок-схема выполнения кода интерпретатором
- Шаг 1: скрипт или .py-файл компилируется, и из него генерируются бинарные данные. Готовый файл имеет расширение .pyc или .pyo.
- Шаг 2: генерируется бинарный файл. Он читается интерпретатором для выполнения инструкций.
Это набор инструкций, которые приводят к финальному результату.
Иногда полезно изучать байткод. Если вы планируете стать опытным Python-программистом, то важно уметь понимать его для написания качественного кода.
Это также пригодится для принятия решений в процессе. Можно обратить внимание на отдельные факторы и понять, почему определенные функции/структуры данных работают быстрее остальных.
Как запускать Python-скрипты?
Для запуска Python-скрипта с помощью командной строки сначала нужно сохранить код в локальный файл.
Возьмем в качестве примера файл, который был сохранен как python_script.py. Сохранить его можно вот так:
- Создать Python-скрипт из командной строки и сохранить его,
- Создать Python-скрипт с помощью текстового редактора или IDE и сохранить его. Просто создайте файл, добавьте код и сохраните как «python_script.py»
Сохранить скрипт в текстовом редакторе достаточно легко. Процесс ничем не отличается от сохранения простого текстового файла.
Но если использовать командную строку, то здесь нужны дополнительные шаги. Во-первых, в самом терминале нужно перейти в директорию, где должен быть сохранен файл. Оказавшись в нужной папке, следует выполнить следующую команду (на linux):
sudo nano python_script.py
После нажатия Enter откроется интерфейс командной строки, который выглядит приблизительно следующим образом:
Теперь можно писать код и с легкостью сохранять его прямо в командной строке.
Как запускать скрипт в командной строке?
Скрипты можно запустить и с помощью команды Python прямо в интерфейсе терминала. Для этого нужно убедиться, что вы указали путь до него или находитесь в той же папке. Для выполнения скрипта (python_script.py) откройте командную строку и напишите python3 python_script.py .
Замените python3 на python , если хотите использовать версию Python2.x.
Вот что будет храниться в самом файле python_script.py:
How to Run Python Scripts on Windows
Python is a general-purpose programming language primarily used to design websites, automate tasks and services, and create web APIs. The Python script is a python file with a “.py” extension. It contains multiple commands to import packages, libraries, and modules. The script file can be runnable on a Python interpreter or shell. However, we can also use the Command Prompt for this purpose.
In this article, we will review the methods used to install Python and execute Python scripts on Windows. So, let’s start!
Install Python on Windows
To run the Python Script, it is required to install Python first on Windows. Go through the below-provided steps to install the latest version of Python on Windows.
Step 1: Download Python Installer
In the first step, visit the below-provided link to download the latest Python installer on Windows:
Step 2: Execute Python Installer
Open the “Downloads” folder and execute the Python installer file:
Step 3: Install Python
Mark the highlighted checkboxes to grant permissions. Then, hit the “Install Now” to install Python on Windows:
You can see that from the below-given output, we have successfully installed Python on Windows:
Let’s check out the method to create the new Python Script file on Windows.
Create Python Script on Windows
To make a new simple Python Script file on Windows, follow the below-given procedure.
Step 1: Create Simple Text File
Firstly, create a simple text file named “PythonProgram.txt”:
Step 2: Change File Extension to “.py”
Next, rename the file and replace the “.txt” extension with “.py”:
The “Rename” alert message will appear on the screen for confirmation. Allow the added changes by hitting the “Yes” button:
Step 3: Open File
Right-click on the file, choose the “open with” option, and then select “Notepad” to open the Python script in Notepad:
Step 4: Add Python Code
Paste the below-provided code into the Python script and press “CTRL+S” to save changes:
Now, let’s go through the method of running the created Python script on Windows.
Run Python Scripts on Windows
Python scripts can be run on a Python interpreter or Windows Command Prompt. To run the Python script on Windows Command Prompt, follow the listed steps.
Step 1: Open Command Prompt
Press “Window+R” to open the “Run” box and type “cmd” in the drop-down menu to open Command Prompt:
Step 2: Move to Python Script Directory
Execute the “cd” command and also define a path where the Python script is placed:
Step 3: Run Python Script
Run the Python script file using “python” command and specify script name as follows:
The below-given output indicates that we have successfully run the created Python script file on our Windows system:
We have elaborated the easiest method to install Python and how to create and run Python script on Windows.
Conclusion
To run the Python script on Windows, it is required to install Python first. For this purpose, visit the Python official website, download the Python installer, and execute it to install Python on Windows. Next, create a simple text file and replace the file extension “.txt” with “.py”. To run the Python script in Windows Command Prompt, utilize the “python [filename.py]” command. We have offered the easiest solution to install Python and run Python script files on Windows.
About the author
Rafia Zafar
I am graduated in computer science. I am a junior technical author here and passionate about Programming and learning new technologies. I have worked in JAVA, HTML 5, CSS3, Bootstrap, and PHP.