Python is one of the leading programming languages in use today. If you are looking to learn programming and choose it as your language, the most important skill you need to learn is how to run a Python script and code.

Python has a relatively simpler syntax compared to other languages. This makes it easier to learn for even those who are in the very early stages of learning. It is the language of choice for developers working with large datasets and data science projects. With a Python training course, you should be able to learn everything about Python and apply your skills effectively.

Difference Between Code, Script and Modules

In computing, codes make up a language that is converted from a language humans understand to one that a computer can understand. Code can also be understood as several small statements coming together to form a program.

A script is a file that consists of a logical sequence of instructions, also known as a batch processing file, that is interpreted by another program instead of by the computer processor. Simply put, a script is a simple program stored in a plain text file that contains Python code. This code can be executed directly by the user. A script is also known as a top-level program file.

Modules refer to a file that contains Python statements and definitions. It is an object in Python with random attributes that developers can bind and reference. Modules are used to break down large programs into small manageable and organised files.

Python - Scripting Language or Programming Language?

The main difference between scripting languages and programming languages is that programming languages are compiled while scripting languages are interpreted. But all scripting languages are considered to be programming languages. Scripting languages are slower than programming languages. They only run on a subset of the programming language, therefore they have less access to the local abilities of a computer.

Python works both as a compiler and an interpreter. That is why it can be called a scripting language as well as a programming language. It can compile Python code into bytecodes and interpret it like Java or C would. However, developers agree that Python can more accurately be described as a general-purpose programming language that works well as a scripting language too.

You May Also Like: Python Certification: A Complete Guide for this Year 2021

The Python Interpreter

An interpreter is a program that you’ll need to run Python scripts and code. It is a software layer that works as an interpreter between your program and computer hardware to run your code. You need to download and install a Python interpreter separately. Depending on which implementation of Python you use, different interpreters are used.

  • A program written using C, for example, CPython, the core implementation of the language
  • A program written using Python, like Jython
  • A program written using Python itself, like PyPy for example
  • A program implemented in .NET such as IronPython

Whichever form of interpreter you use, your code will always be run by this program. This is why having the interpreter correctly installed on your system is the first step to running your Python scripts.

An interpreter runs Python code in one of two ways

  1. As a script or module
  2. As a piece of code typed into an interactive session

How to Run Python Code Interactively

To start an interactive session using Python, open a command-line or terminal and type in ‘python’ or ‘python3’ (depending on your Python installation) and hit Enter.

The standard prompt for interactive mode is ‘>>>’. As soon as you see these marking characters, you’ll know you are in. Once you are in, you can write your Python code, but the only drawback is that when you close the session, your code will disappear too.

When you work interactively, all your statements are executed immediately. This allows you to test every piece of code, making it a great tool for developers and a cool way to experiment with Python and test code on the go.

To exit interactive mode, follow one of these sets of steps

  • Use quit() or exit() which are built-in functions
  • Ctrl+Z and Enter on Windows
  • Ctrl+D on Unix-based and similar systems

If you’ve never worked with the command-line or terminal, try the following.

  • Windows - The command line is known as a command prompt, a program called cmd.exe. The quick way to access it is by using ‘Windows+R’ to open the Run dialog box. Type cmd into the prompt and hit Enter.
  • GNU/ Linux and other Unix systems - Several applications can grant you access to the system command line. Gnome Terminal, xterm and Konsole are some of the most popular ones. These are tools that run a shell or terminal, such as Bash, ksh, csh etc. On these systems, the path to these applications is more varied and depends on your desktop environment and distribution.
  • Mac OS - The system terminal can be accessed by clicking on Applications, then Utilities and finally Terminal.

Running Python Scripts by the Interpreter

The multi-step process used to run Python scripts is called the Python Execution Model.

1. First, the statements or expressions of your script are processed sequentially by the interpreter.

2. After this, the code is compiled into bytecode, a form of instructions that can be understood by the hardware. In this step, the code is converted into a low-level language. Bytecode is an intermediate machine-dependent code that optimises the code execution process. The interpreter, therefore, ignores the step of compilation the next time.

3. Finally, the code is transferred for execution by the interpreter. The Python Virtual Machine (PVM) is the final step of the Python interpreter process. It is a fundamental part of the Python environment on your system. It loads the bytecode in the Python runtime. It then reads and executes each operation as indicated. It’s the component that actually runs your scripts.

Running Python Scripts Using Command-Line

The most aspired way of writing a Python program is by using a plain text editor. The code written in an interactive session is lost once you close the session, although it allows you to write a significant amount of code. On Windows, these files use the .py extension.

If you are just starting to use Python, you can use Notepad++ or similar text editors that are very easy to use.

Once you’ve got your editor, open a file and write the following code:

print(‘Hello World!’)

Save the file on your desktop. Remember you can only do so using a .py extension.

Using The python Command

The easiest and simplest way to run Python scripts is by using the python command. Open the command-line and type the word ‘python’ followed by the path to your script file and then hit Enter. It looks like this:

python first_script.py

Hello World

As soon as you do this, the phrase ‘Hello World’ will come up on your screen. If you do not see this output, check your system path and the place where you saved your file. If it still doesn’t work, reinstall Python on your system and try again.

Redirecting output

Windows and Unix-based systems use a process called stream redirection. It lets you redirect the output of your stream to a different file format instead of the standard system output. Saving the output in a different file can prove useful to analyse later.

Here’s an example of how you can do this:

python first_script.py > output.txt

When you do this, your Python script is redirected to the ‘output.txt’ file. If the file doesn’t exist, it is created by the system. If the file already exists, the contents of the file are replaced.

Additional Read: A Complete Guide for Splunk Certification

Running modules with the -m option

A module is a file that contains your Python code. It allows you to arrange your code logically, and defines functions, classes and variables. It also includes code you can run. If you want to run a Python module, Python offers several command-line options that vary according to the needs of the user. One of these commands is

python -m <module-name>

This command searches for the module name in the ‘sys.path’ and runs the content as

__main__:

python -m first_script

Hello World

Using Script Filename

To run a Python script, Windows uses system registers and file associations. By entering the name of the file containing the code, it determines the program needed to run that specific file. Consider the following example using the command prompt.

C:\Users\Local\Python\Python37>first_script.py

Hello World

If you are using a Unix-based system, you need to add a line before the text -

#!/usr/bin/env python.

Python doesn’t read this line, but it is more for the benefit of the operating system. It helps the system to decide what program it should use to run the file. The character combination #! is known as shebang or hashbang. This is how the line starts, followed by the interpreter path.

To run scripts, execution permissions need to be assigned and the hashbang line needs to be configured. Finally, type in the filename in the command line.

If this doesn’t work, check if the script is located in your current working directory. Else you can use the file path for this method.

Running Python Scripts using an IDE or a Text Editor

An Integrated Development Environment (IDE) is an application that lets you build software within an integrated environment over and above the required tools. You can use Python IDLE, Python Distribution’s default IDE, to write, debug, modify and run modules and scripts. Other IDEs you can use are Spyder, PyCharm, Eclipse and Jupyter Notebook.

If you want to run a Python script from your IDE, create a project first. Then add your .py file to it, or alternatively, create one using the IDE. When you run it, you’ll see the output on your screen.

Running Python Scripts from a File Manager

You can also run your Python script in a file manager. This option is mainly used in the production stage after the source code is released. Simply double-click on the file icon. However, make sure some conditions are met.

  • Windows - Run your script by double-clicking on the file. Save your script file with a .py extension for ‘python.exe’ and .pyw for ‘pythonw.exe’.
    If you’re using the command-line, you might see a black window flash on your screen. Include a statement at the tail of your script ‘input(‘Enter’)’. This will exit the program only when you press Enter. The ‘input()’ function will only work if your code is error-free.
  • GNU/ Linux - Your Python script must carry the hashbang line and execution permissions. If not, the double-click won’t work in your file manager.
    Executing a script by double-clicking on the file is easy, but it isn’t a preferred method. This is because it has many limitations and dependency factors, like the operating system, the file manager, execution permissions and file associations. Developers suggest using this option only after the code is debugged and ready for the production market.

Enroll in a Python Course today to enhance your Python skills and increase your efficiency.

Armin Vans
Aarav Goel has top education industry knowledge with 4 years of experience. Being a passionate blogger also does blogging on the technology niche.

COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here
You have entered an incorrect email address!
Please enter your email address here

Loading...

Submitted Successfully...