How To Run a Python Script – Beginners Guide
In this post, we will walk through the basic concepts, different ways, and environment setup that is required to run a python script.
Following are the prerequisites to run a python script.
1. The first and foremost thing is the python environment to run and test your scripts. You can download and install the latest version of python in your system from this link
2. Use Atom, Sublime or Visual studio code as a text editor. I would strongly suggest the open-source visual studio code, as it is packed with good features for coding with an integrated terminal. Also, it supports auto-completion, debugging, and much more.
Creating Your First Python Script
For most of the system administration tasks, you would create a bash script which runs in a shell. In the same way, you can create a python script that runs in a shell.
The first thing you are going to do is create a project folder named python and create the following two files with
.sh and .
Copy the following contents on the two files using your editor.
#!/usr/bin/env python3 # My first python Script print ("Hello Python User")
1. In the above code,
#!/usr/bin/env python3 represents the run-time environment for the program. Normally in bash scripts, you would have
#! /bin/bash we are using python 3 (latest python) for our program. I would suggest you to go with python 3 and not python 2.
# My first python Script is just a comment. Every comment starts with
print ("Hello Python User") is just a python print function which outputs “hello python User”.
Execute Python Script
To run the
.sh script, first, change it to an executable format by executing the following commands in the terminal.
chmod +x first.sh
2. To execute the script, you can use any of the following commands.
./first.sh python first.sh ./first.py python first.py
All the above executions will display the same output. So script file extension and execution is your choice. But our recommendation is to stick with .py extension and develop your scripts using a good editor like VS code that supports python linting, debugging and autocompletion.
In this tutorial, you created your first python script and executed it. In the next tutorial, we will look into more python-based concepts.
Also, look at our comprehensive guide on Python for Devops where we explain why python is very important for automation tasks.