官术网_书友最值得收藏!

A readable script

As network automation/DevOps engineers, we often tend to overlook the way we write a script. The focus is always on providing accurate results, which is great, but as we scale our script or application, a focus on the readability of the script is essential.

This becomes a key requirement when we start to work as a team where we have multiple contributors for a script or set of scripts.

Let's look at an example of a bad Python script that returns the result as expected (output is correct):

 x=input("What is your name:")
print ("how are you"+x)
y="how are you"+x
if ("test1" in y) and ("test2" in y):
print ("cool")
x=y.split(" ")
x=x[2]+"awesome"
if ("are" in x):
print ("not cool")

After the second or third line of code as we read through, we lose the understanding of program flow, and what the expected result was.  Eventually, it becomes very difficult to interpret even a simple script such as this.

Imagine how difficult it would be for someone who has not written this code to interpret a bigger script (say, 50 lines).

Now, let's modify this code to make it readable:

#ask for input of user's name and prints it with a message
x=input("What is your name:")
print ("how are you"+x)
y="how are you"+x

#validates and prints message if 'test1' AND 'test2' exists in input
if ("test1" in y) and ("test2" in y):
print ("cool")

#splits the sentence stored in variable x with blank spaces
x=y.split(" ")
print (x)
#adds the string "awesome" to the third word in the sentence and stores it in x
x=x[2]+"awesome"

#validates if word "are" is in x and prints the message accordingly
if ("are" in x):
print ("not cool")

As we can see, each section (or line) that achieves a specific result is tagged by a remark line (denoted by #). This line is a human-readable line that is ignored by the program (or compiler) and is used to ensure any reader of the program understands what is going on in each section. This ensures that each and every aspect of the script is easily understood by the reader; as the script is enhanced, troubleshooting and modifications in the program become very easy.

Another key aspect in the readability of a program is to ensure we add some key information at the very start of the code.

A generic suggestion would be to include the following:

  • The author's name
  • Version of the script (starts with 1.0)
  • One-liner description of basic usage of the script
  • Any specific installation requirements

As an example, let 's add this to the very top of the preceding script:

#Name: Abhishek Ratan
#Version: 1.0
#Usage: Asks for user input and validates it for some specific keywords
#Additional installation required: None
主站蜘蛛池模板: 肃南| 乐安县| 江口县| 南川市| 阜平县| 安泽县| 巩留县| 榕江县| 建湖县| 托克逊县| 巴中市| 桐乡市| 洱源县| 榆树市| 娄底市| 法库县| 宜君县| 霍州市| 鄱阳县| 资源县| 诸暨市| 封开县| 江达县| 娄烦县| 江源县| 盘锦市| 阿鲁科尔沁旗| 东源县| 青铜峡市| 浦城县| 凤凰县| 江达县| 乐至县| 天长市| 垫江县| 肇庆市| 鄂温| 澜沧| 屯门区| 徐水县| 乐亭县|