How To Run A Python Script: A Comprehensive Guide

  1. Home
  2. Technical Tutoring Tips
  3. How To Run A Python Script: A Comprehensive Guide

Subject: Computer Science - Other

Field: Computer Science


How To Run A Python Script: A Comprehensive Guide

 


Image source

There are numerous different languages programmers use when coding from JavaScript and HTML to PHP, CSS and SQL. As technologies and applications evolve, the list grows longer each year. But if there is one programming language that presently reigns supreme, it is Python.

It has been around for years, helping create several popular tools and platforms such as Google Search and YouTube. Despite Python’s simple syntax, it is the backbone of many operations.

The beauty of Python is that it can be used by both beginners and experienced coders alike. But when you’re just starting out, it’s very important to learn how to run Python code, because computers can’t actually understand it. To ensure the human-written code becomes machine-understandable, you need an interpreter that will tell you if the code is working, and a script that will store all of your Python commands.

This may seem overwhelming for beginners but when you get into it, running Python scripts will be second nature. This guide will help you understand how to run Python scripts with ease.

What is a Python script?

A Python script, also known as a Python program, is a collection of commands that are stored in a file. There might be function definitions in the script as well as the main program.

A Python script is saved as a .py file extension. This script is a file that can contain a batch processing file or a logical sequence of orders. And since it’s stored in a plain text file, it’s typically a very simple program. An interpreter is responsible for processing these scripts and executing each command chronologically.

A Python code within a plain text file is called a script if it is intended to be directly executed by the user. The formal term for a script is ‘top-level program file’.

However, we also have modules, which are plain text files that contain Python code that is meant to be imported and used from a different Python file.

In other words, scripts and modules are very similar and their only difference is that scripts are designed to be directly executed, while modules are designed to be imported. Regardless of whether you’re writing modules or scripts, you should learn how to run your Python code.

What is a Python interpreter?


Image source

An application that programmers use to run their scripts is called a Python interpreter. With it, you have access to history substitution, interactive editing, and similar features. It uses a sequential order to process the Python commands that are in your script.

A Python interpreter translates the Python code into a lower-level language called byte code, before running that language over Python Virtual Machine (PVM).

There are different types of interpreters and they differ based on the implementation you use:

  • A program that was written in C (for example, CPython).
  • A program written in Python (for example, PyPy).
  • A program that was written in Java (e.g. Jython).
  • A program that was implemented in .NET (such as IronPython).

Whatever type of interpreter you use, the code you run will always be run by this program, so it’s essential that you install the interpreter correctly on your system.

Finally, there are two different ways your interpreter will be able to run your Python code. The first is as a simple script or module as we’ve already mentioned, and the second is as a piece of code typed into an interactive session.

How to access Python prompts

Before you can learn how to run a Python script, you should know how to access a Python command prompt. To do this, you need to install Python on your machine and run the script file.

This works differently on different operating systems:

  • Windows. Open the command prompt by typing cmd in the Run box (Windows button), find Python in the directory, and run it on the command line.
  • Mac. Go to the terminal in your launchpad and type Python. From there, you will be taken to the Python prompt.
  • Linux. Open terminals by right-clicking on Desktop, type Python and run it.

How to run a Python script


Image source

One of the first things programmers find out when learning how to run a Python script is that it can be done in four different ways. Let’s go through all of them.

Interactively

One of the most common ways to run Python code is interactively. When you want to start an interactive session, you need to open your terminal or command-line, type Python and press Enter.

When you run Python in interactive mode, you can go to the Python prompt and write the script line-by-line. Another thing you need to know is the standard prompt for this mode is >>>. Also, as soon as you write out a statement, it will be executed immediately.

Let’s look at an example:

  • >>> print('Hello World!')

Hello World!

  • >>> 2 + 5

7

  • >>> print('Welcome to Real Python!')

Welcome to Real Python!

One of the reasons why the interactive mode is such a good development tool is because it allows you to test out every piece of code you write out to ensure it works correctly.

If you’re unsure about what a piece of Python code does, the best course of action would be to launch an interactive session and see for yourself.

The only drawback to the interactive method is that your code won’t be saved when you close the session.

From an IDE or text editor

When you need to develop larger applications that are more complex, you need to use an IDE (integrated development environment) or an advanced options text editor. An example of this is PyCharm.

Most IDE programs allow you to run the scripts inside the environment itself and they often have a Build or Run command which is located in the toolbar or in the main menu.

The default IDE in the standard distribution for Python is IDLE which you can use to debug, write, modify, and run your scripts and modules.

If you want to run your script from a text editor such as VS Code, you first need to add the Python extension. To do this, you need to go to the Extensions section and install Python and code runner extensions. Once that is done, you need to restart your VS code.

With the command line

As we already mentioned when talking about interactive sessions, it is possible to write many lines of code. But when you’re using the interactive method, you will lose all of the code you have written as soon as you close the session.

This is why most programmers use plain text files when they’re writing Python programs. These files will be saved with the .py extensions or sometimes .pyw when using the Windows operating system.

You can use any plain text editor to create Python code files. If you’re still a beginner, you should choose an easy-to-use editor that is also powerful (e.g. Sublime Text), but the choice is up to you since most editors will work fine.

Let’s look at an example of how you can run a Python script from the command line. Open a text file by using your chosen editor, and type in the following code:

Name = "John"

print("Hello" + Name)

Then, you need to save the file in hello.py format. Go to the command line to find the folder where you stored the Python file. From there, you will give the following command and click Enter:

cd

Python hello.py

Once you have done that, you will be presented with an output that reads “Hello John”.

From a file manager

Finally, another way you can run a Python script is to go to a file manager and double-click on its icon. This method isn’t used too frequently in the development stage, but programmers sometimes use it when they are ready to release their code for production.

To be able to run your scripts this way, you need to satisfy some conditions first, and those conditions will depend on the operating system you use.

If you use Windows, it will associate the extensions .py with the program Python.exe and .pyw with Pythonw.exe. You will need this to run your scripts by double-clicking them.

If your script has a command-line interface, you will probably run into the problem of seeing a black window flash on your screen. You can easily fix that by adding a statement:

input('Press Enter to Continue...')

If you use Unix-based operating systems, you will most likely be able to go to your file manager and double-click your Python file to run it. These scripts will need to have execution permission and will require the above-mentioned trick against a flashing black window.

However, it’s important to note that this method has several limitations, and it is best to use it when your scripts are ready to go into production and debugged.

What else should you know when running Python scripts?

Now that we’ve gone through the basics of how to run a Python script, let’s look at some other things you should know.

Logging

First of all, you shouldn’t print your statements in the console. Instead, you should probably save them in a separate Python file. That way, they won’t be temporary and you will always be able to come back to them. This is known as logging and there is a built-in function for it in Python.

It goes like this:

# import

import logging

# config the logging behavior

logging.basicConfig(filename='example.log’,level=logging.DEBUG)

# some sample log messages

logging.debug(‘This message should go to the log file’)

logging.info(‘So should this’)

logging.warning(‘And this, too’)

There are also a few logging levels that you can use:

  • DEBUG - Detailed information, typically of interest only when diagnosing problems.
  • INFO - To confirm that everything is working as expected.
  • WARNING - An indication that something happened unexpectedly, or might become an issue in the near future (e.g. ‘disk space low’). The software is still working as expected.
  • ERROR - Due to a more serious problem, the software has not been able to perform some function.
  • CRITICAL - A serious error, indicating that the program itself may be unable to continue running.

Documentation

If you want to maintain your code, you need to document it. While it may seem hard to create documentation, it is quite easy once you get the hang of it.

There are some open-source tools such as sphinx and pydoc which you can use to create full-fledged HTML documentation, both of which come with how-to steps.

If you are using Kedro, you can run the command ‘kedro build-docs –open‘ and the documentation will automatically be opened in your default browser.

Virtual environment

Virtual environment, or VE for short, is the local copy of the Python environment which is like a blank slate and any package can be installed in the VE separately. Every new project needs to have its own VE because you can use it to install anything you want without affecting your system.

To create a VE, you need to run the command ‘Python3 -m venv tutorial-env’ at the project root directory. To activate it, all you need to do is run the command tutorial-env\Scripts\activate.bat. If you use Unix or macOS, you need to source tutorial-env/bin/activate.

Summary

Learning how to run a Python script is one of the first things anyone who is looking to start a career in software development needs. This knowledge will provide you with strong fundamentals that will make your development process much faster and turn you into an expert programmer in no time.

While this tutorial isn’t too extensive or overly complicated, it provides you with the knowledge you need to have if you’re just starting out and coding seems intimidating to you. But there is no reason to worry or feel insecure, because if you take it step by step, you won’t have any issues.

In case you’re one of those students that need one-on-one help when dealing with homework or understanding the subject, you can always look for a tutor online to help you master Python.

Meta Description: Knowing Python is one of the most sought-after coding skills by HR recruiters. Learn how to run a python script with this comprehensive beginner’s guide.

Live Chats