In this post, we will walk through the basic concepts and environment setup that is required to learn python scripting.
1. The first and foremost thing is python environment to run and test your scripts. You can download and install the latest version of python in your system from this link https://www.python.org/downloads/
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 You 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 .py extensions.
Copy the following contents on the two files using your editor.
# 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”.
Executing your first python Script
We save our python script in .sh and .py format.
1. To run the .sh and .py scripts, first, change it to an executable format by executing the following commands in the terminal.
chmod +x first.sh
chmod +x first.py
2. To execute the script, you can use any of the following commands.
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.