Skip to main content

How to Run Python Scripts Tutorial

Learn how you can execute a Python script from the command line, and also how you can provide command line arguments to your script.
Updated Dec 21, 2022  · 10 min read

Run and edit the code from this tutorial online

Run code

Typically, every novice learns to write a Python script on the command line first, then moves to execute the script from the command line, wherein the script is usually written in a text editor and is run from the command line. In this post, we explore in more detail how to run Python scripts. 

Python Scripts and Interpreters

Computers cannot understand code in the way humans write it, and hence, you need an interpreter between the computer and the human-written code. The interpreter's job is to convert the code into a format that computers can then understand and process.

The interpreter processes the code in the following ways:

  • Processes the Python script in a sequence

  • Compiles the code into a byte code format which is a lower-level language understood by the computers.

  • Finally, a Python Virtual Machine (PVM) comes into the picture. The PVM is the runtime powerhouse of Python. It is a process that iterates over the instructions of your low-level bytecode code to run them one by one.

Like scripts, you have something called Module, which is a Python script imported and used in another Python script.

The Python script is saved with a .py extension which informs the computer that it is a Python program script. Unlike Windows, Unix-based operating systems such as Linux and Mac come with Python pre-installed. Also, the way Python scripts are run in Windows and Unix operating systems differ.

Running Python Scripts: Getting Set Up

For all users, especially Windows OS users, it is highly recommended that you install Anaconda, which can be downloaded from the Anaconda website. You can follow along with the instructions given in this installing anaconda for Windows tutorial.

To install Python3 on a Windows operating system, please feel free to check out this Python setup tutorial.

Command-line interpreter for Python can be accessed on the various operating systems in the following ways:

  • On Windows, the command line is known as the command prompt, which can be accessed by clicking the start menu and search for command prompt. Another way is by going to the Run dialog box type cmd and press enter (Start menu $->$ Run and type cmd). After which, if Python is installed in your C-drive then all you have to do is type C:\python36\python.exe, where python36 is the Python version (Note: This path may vary based on the directory at which Python is configured).
command prompt
(Source)
  • On a Mac system, it is very straightforward. All you need to do is open Launchpad and search for Terminal, and in the terminal, type Python , and it will give you an output with the Python version.
mac system
  • Like the Mac system, accessing the terminal on a Linux system is also very easy. Right-click on the desktop and click Terminal in terminal type Python.
linux system
(Source)

Note: In this tutorial, you will learn using the Mac OS Terminal.

So without further ado, let's get started!

Master your data skills with DataCamp

Learn the skills you need at your own pace—from non-coding essentials to data science and machine learning.

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.

Writing Python Scripts in the Terminal

Let's see how we can code and generate the output in the terminal itself. To accomplish this, first, you will type python3, which means you will be using Python3 version.

After which, you can code typically as you would in a text editor or an IDE (integrated development environment), though you will not be getting the functionalities in the terminal as you would get with an IDE.

You will start with the evergreen Hello, World! example, and let's see what the output looks like in the terminal.

Writing the Python Script in Terminal

Isn't it nice how by just opening the terminal and typing Python3, you can code in Python? Let's try some more examples.

Writing the Python Script in Terminal

One thing to notice in the above example is that, without even typing the print statement, you were able to get the output.

Let's complicate the code a bit and lets you use the NumPy (Numerical Python) library to create two arrays and apply a few mathematical operations on it. For a little background on numpy, it is a Python programming library that has the capability of dealing with large, multi-dimensional arrays and matrices, along with an extensive collection of high-level mathematical functions to operate on these arrays.

Writing the Python Script in Terminal

You can observe from the above figure that using numpy; you were able to create, add, and multiply two numpy arrays within the terminal. One thing to note here is that the multiply function in numpy does an element-wise multiplication while dot function takes the dot product of two matrices. To accomplish the np.dot command, you need to make sure that the columns of the first matrix are equal to the rows of the second matrix and hence, the value error.

How to Run Python Scripts From the Terminal

Running the Python script from the terminal is very simple, instead of writing the Python script in the terminal all you need to do is use a text editor like vim, emacs or notepad++ and save it with a .py extension. Then, open the terminal and go to the directory where the code resides and run the script with a keyword python followed by the script name.

Running the .py script from the Terminal

To create the terminal.py file, use vim in the terminal with the program name as vim terminal.py and paste the below code in it. To save the code, press esc key followed by wq!. And finally, to run that script, all you need to do is type python3 terminal.py , and within less than a second, you will see the output as shown above.

The following is the code used in the above example.

import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
# [[ 6.0  8.0]
#  [10.0 12.0]]
print("Output of adding x and y with a '+' operator:",x + y)
print("Output of adding x and y using 'numpy.add':",np.add(x, y))

# Elementwise difference; both produce the array
# [[-4.0 -4.0]
#  [-4.0 -4.0]]
print("Output of subtracting x and y with a '-' operator:",x - y)
print("Output of subtracting x and y using 'numpy.subtract':",np.subtract(x, y))

# Elementwise product; both produce the array
# [[ 5.0 12.0]
#  [21.0 32.0]]
print("Output of elementwise product of x and y with a '*' operator:",x * y)
print("Output of element wise product of x and y using 'numpy.multiply':",np.multiply(x, y))

# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print("Output of elementwise division x and y with a '/' operator:",x / y)
print("Output of elementwise division x and y using 'numpy.divide':",np.divide(x, y))

# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print("Output of elementwise square root x using 'numpy.sqrt':",np.sqrt(x))
Output of adding x and y with a '+' operator: [[ 6.  8.]
 [10. 12.]]
Output of adding x and y using 'numpy.add': [[ 6.  8.]
 [10. 12.]]
Output of subtracting x and y with a '-' operator: [[-4. -4.]
 [-4. -4.]]
Output of subtracting x and y using 'numpy.subtract': [[-4. -4.]
 [-4. -4.]]
Output of elementwise product of x and y with a '*' operator: [[ 5. 12.]
 [21. 32.]]
Output of element wise product of x and y using 'numpy.multiply': [[ 5. 12.]
 [21. 32.]]
Output of elementwise division x and y with a '/' operator: [[0.2        0.33333333]
 [0.42857143 0.5       ]]
Output of elementwise division x and y using 'numpy.divide': [[0.2        0.33333333]
 [0.42857143 0.5       ]]
Output of elementwise square root x using 'numpy.sqrt': [[1.         1.41421356]
 [1.73205081 2.        ]]

Passing Command Line Arguments to Python Script

Command line arguments make life a lot easier, many times in production-ready code command line arguments are used. It makes the code output reproducibility efficient. For example, let's say your code has a lot of user inputs or files that are being read, then by using command line arguments, you will not have to go into the code to do all of these changes in case you need to change the file name or a variable input.

To accomplish this, you will make use of the sys module, which is an in-built Python module. Within sys, you have argv which gives you the list of command-line arguments passed to the Python program. sys.argv reads the command line arguments as a list of items where the first item/element in that list can be accessed as sys.argv[1] while the first argument, i.e., sys.argv[0] is always the name of the program as it was invoked.

Let's take a simple example and see how it works.

Note: The command line argument is read as a string by Python, so make sure to convert it as an integer in case you are dealing with numbers.

Much like the previous example, save the below lines of code in an editor as command_line.py and to run the code type python3 command_line.py 10 where 10 is the command line argument.

import sys
num = sys.argv[1]
for i in range(int(num)):
    print (i)
Passing Command Line Arguments to Python Script

What if you do not provide any command line argument?

You will get an error list index out of range, which also reinforces that sys.argv reads as a list of items. To avoid such errors, you need exceptional handling, which is out of the scope of this tutorial.

Passing Command Line Arguments to Python Script

Writing the Output of a Python Script to a File

Finally, as a bonus, let's see how you can save the output of the Python script in a txt file using the > key. 

You will first create a folder cli and move the command_line.py code in the cli folder. Then, you will check what is there in that folder to make sure there is no txt file already existing.

Then, you will type python3 command_line.py 10 > output.txt and finally check the content of the cli folder. Now, you should be able to see the output.txt file.

Writing the Output of Python Script to a File

Let's open and see the content of the output.txt file.

Writing the Output of Python Script to a File

From the above output, you can see that the 0-9 digits have now been written in a text file using just a > sign.

Conclusion

Congratulations on finishing the tutorial.

There is still a lot to be explored, like GUI-based execution in Python, running Python scripts interactively, and running Python scripts from a file manager or from an IDE. Specific to command line execution, you might want to experiment on the Windows command prompt and see how it is different from a Unix-based operating system.

If you are just getting started in Python and would like to learn more, take DataCamp's Introduction to Data Science in Python course.

Python Scripts FAQs

What is a Python script?

A Python script is a file that contains Python code. The code in a Python script can be executed by running the script, either from the command line or by calling it from another script.

How do I create a Python script?

To create a Python script, you will need a text editor or an integrated development environment (IDE) that is capable of writing and saving Python code. Some popular IDEs for Python include PyCharm, IDLE, and Visual Studio Code.

To create a new Python script, simply create a new file and save it with a .py extension. Then, you can write your Python code in the file and save it to run the script.

Can I run a Python script in the background?

Yes, you can run a Python script in the background by using the nohup command. For example:

nohup python script.py &

This will run the script in the background and allow you to continue using the terminal while the script is running.

How do I run a Python script from the command line?

To run a Python script from the command line, you will need to have Python installed on your system. Then, you can use the following command to execute a script:

python script.py
Topics

Python Courses

course

Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

How to Install Python on macOS and Windows

Learn how to install Python on your personal machine with this step-by-step tutorial. Whether you’re a Windows or macOS user, discover various methods for getting started with Python on your machine.
Richie Cotton's photo

Richie Cotton

14 min

tutorial

Argument Parsing in Python

In this tutorial, learn how to parse one or more arguments from the command-line or terminal using the getopt, sys, and argparse modules.
Sayak Paul's photo

Sayak Paul

10 min

tutorial

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

tutorial

Running Python Scripts in Power BI Tutorial

Discover the different ways you can use Python to optimize data analysis, visualization, and modeling in Power BI.
Joleen Bothma's photo

Joleen Bothma

9 min

tutorial

Python Print() Function

Learn how you can leverage the capability of a simple Python Print function in various ways with the help of examples.
Aditya Sharma's photo

Aditya Sharma

10 min

tutorial

Python Functions: How to Call & Write Functions

Discover how to write reusable and efficient Python functions. Master parameters, return statements, and advanced topics like lambda functions. Organize your code better with main() and other best practices.
Karlijn Willems's photo

Karlijn Willems

14 min

See MoreSee More