How To Run Your Python Scripts

Read it in 8 Mins

Last updated on
07th Jun, 2022
Published
16th Jul, 2019
Views
3,983
How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python script and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not. To know more about sys.argv command line argument, click here.   

Python, being one of the leading programming languages, has a relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.

Also, know how to use Self in Python by visiting the given link.

What is the difference between Code, Script and Modules?

In computing, the code is a language that is converted from a human language into a set of ‘words’ that the computer can understand. It is also referred to as a piece of statements together that forms a program. A simple function or a statement can also be considered a code.

On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.

In simple terms, a script is a simple program, stored in plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file

A module is an object in Python with random attributes that you can bind and reference.

Is Python a Programming Language or a Scripting Language?

Is Python a Programming Language or a Scripting Language?

Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted

Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. 

Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.

However, considering the historical relationship between the general-purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language that works nicely as a scripting language too.

The Python Interpreter

The Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application that is responsible for running Python scripts.

The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.

  • Reads the command.
  • Evaluates the command.
  • Prints the result.
  • Loops back and process gets repeated.

The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.

A Python Interpreter runs code in two ways— 

  • In the form of a script or module.
  • In the form of a piece of code written in an interactive session.

Starting the Python Interpreter

The simplest way to start the interpreter is to open the terminal and then use the interpreter from the command line.

To open the command-line interpreter:

  • On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu  Run and type cmd.
  • On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.
  • On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal

Running Python Code Interactively

Running Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.

To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.

An example of how to do this on Windows:

C:\users>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>

The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.

The statements you write when working with an interactive session are evaluated and executed immediately:

print('HELLO WORLD!')
HELLO WORLD!
2 + 3
5
print('Welcome to the world of PYTHON')
Welcome to the world of PYTHON 

The only disadvantage is when you close the interactive session, the code no longer exists.

How to Run Python Script by the Interpreter

The term Python Execution Model is given to the entire multi-step process to run Python script.

  1. At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. 
  2. Then the code is compiled into a form of instruction set called the bytecode.
    Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code that optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.
  3. Finally, the interpreter transfers the code for execution.
    The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component that actually runs your scripts.

How to Run Python Script using Command-Line

The most sought-after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  

If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.

Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:

print('Hello World!')

Then save the file on your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.

Using python command

The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this:

python first_script.py
Hello World!

Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. 

However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.

Redirecting output

Windows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.

An example of how you can do this:

python first_script.py > output.txt

What happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.

Running modules with the -m option

A module is a file that contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.

If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command 

 python -m <module-name>. 

It searches the module name in the sys.path and runs the content as

 __main__:
python -m first_script
Hello World!

Note that the module-name is a module object and not any string.

Using Script Filename

Windows makes use of the system registers and file association to run Python script. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.

An example of how to do this using command prompt:

C:\Users\Local\Python\Python37> first_script.py
Hello World!

On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.

The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.

Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:

#Assign the execution permissions
chmod +x first_script.py
#Run script using its filename
./first_script.py
Hello World!

However, if it doesn’t work, you might want to check if the script is located in your current

working directory or not. Otherwise, you can use the path of the file for this method. 

How to Run Python Script Interactively

As we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.

Using import

Importing a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. 

An implementation of the import:

import first_script
Hello World!

You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.

One important thing to note is that the import option works only once per session. This is because these operations are expensive.

For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.

You can run the code below to know what’s in your current PSMP:

import sys
for path in sys.path:
print(path)
\Users\Local\Python37\Lib\idlelib
\Users\Local\Python37\python37.zip
\Users\Local\Python37\DLLs
\Users\Local\Python37\lib
\Users\Local\Python37
\Users\Local\Python37\lib\site-packages

You’ll get the list of directories and .zip files where your modules and packages are imported.

Using importlib

importlib is a module that is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.

An example to perform this:

import importlib
importlib.import_module('first_script')
Hello World!
<module 'first_script' from '\Users\Local\Python37\first_script.py'>

importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.

The following code shows that:

import first_script #First import
Hello World!
import first_script
import importlib #Second import does nothing
importlib.reload(first_script)
Hello World!
<module 'first_script' from '\Users\Local\Python37\\first_script.py'>

However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:

importlib.reload(first_script)
Traceback (most recent call last):
...
...
  raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

Using runpy.run_module() and runpy.run_path()

The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. 

The module is located using import and then executed. The first argument of the run_module() must contain a string:

import runpy
runpy.run_module(mod_name='first_script')
Hello World!
{'__name__': 'first_script',
    ...
'_': None}}

Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.

An example of such is as follows:

import runpy
runpy.run_path(file_path='first_script.py')
Hello World!
{'__name__': '<run_path>',
    ...
'_': None}}

Both the functions return the globals dictionary of the executed module.

Run Python script Using exec()

Other than the most commonly used ways to run Python script, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.

An example of exec() is:

exec(open('first_script.py').read())
Hello World!

Run Python Script Using py_compile

py_compile is a module that behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.

You can compile your Python script using this module:

import py_compile
py_compile.compile('first_script.py' 
'__pycache__\\first_script.cpython-37.pyc' 

The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.

Running Python Scripts using an IDE or a Text Editor

An Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.

You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.

You can also use popular text editors like Sublime and Atom to run Python script.

If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output on your screen.

Running Python Scripts from a File Manager

If you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.

However, to achieve this, some conditions must be met:

  • On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.

If you are using the command line for running your script, you might likely come through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.

  • On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.

Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.

So it is suggested to use this option only after the code is debugged and ready to be in the production market.

Conclusion

Working with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality, and so on. They are also used to automate complex tasks in a simplified manner.

In this article, you have learned to run advanced python scripts using:  

  • The terminal or the command-line of the operating system.
  • The Python Interactive session.
  • Your favorite IDE or text editor.
  • The system file manager.

Here, you have gathered the knowledge and skills of how to run your scripts using various techniques. You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques with Knowledgehut python programming courses. 

Profile

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.