Python Scripts vs Bash

    It's no secret that in terms of automating any simple actions, both versions of the scripts are a powerful tool. I read this little article and thought - why are we worse? I’ll take it and describe how to automate simple console actions using python scripts, even though this topic is quite wide.

    Go!


    To make a Python script executable in the console, you need the first line to look like

    #!/usr/bin/python

    where / usr / bin / python is the address of the Python interpreter installed on your system. Well, of course, the user running the script must have permission to execute it. Typically, this will only work on NIX systems. On Windows, scripts automatically become executable when a correspondence is established between the interpreter and the .py file type .

    In general, Python scripts are in many ways similar to Bash scripts, however, in my opinion, they are much more elegant. Consider the main functions that we may need:

    listdir(path)
    Returns a list of file and folder names in a folder named path.

    mkdir(path)
    Creates a folder called path.

    makedirs(path)
    It works similarly to the mkdir () function, but automatically creates all the necessary intermediate folders.

    remove(path)
    Deletes a file named path.

    rmdir(path)
    Deletes a directory named path.

    removedirs(path)
    It works similarly to the rmdir () function, but it automatically deletes all parent empty folders.

    rename(src, dst)
    Renames a file or folder named src to dst.

    open(filename, flag)
    Opens a file named filename. Flag is needed to determine the access mode: "r" - read, "w" - write, "a" - append.

    read(size)
    Reads size data from a file and returns as a string. If the argument is omitted, then the entire contents of the file are read.

    readline()
    Reads one line from the file, including the newline character ("\ n").

    readlines()
    Reads all lines from a file and returns them as a list.

    write(string)
    Writes a string to a file.

    writelines(lines)
    Writes lines from the lines list to a file. A newline is not added between them.

    tell()
    Returns the current position in the file in bytes from the beginning of the file.

    seek(offset, whence)
    Changes the position to offset. The nature of the position determination depends on the argument whence (default 0):
    1) 0 - the new position is counted from the beginning of the file;
    2) 1 - from the end of the file;
    3) 2 - from the current position in the file;

    truncate(size)
    Truncates the file to size size.

    close()
    Close the file. Remember! Any opening of the file should be followed by a subsequent closing using this method.

    And now - to more special cases.


    Mess in my head? Nothing, now we will analyze all the details.

    The first thing to add is a bit of interactivity. Otherwise, the meaning in our script, if he will not ask the user for anything? :) For input from the keyboard, the raw_input () method is used . Why not just input () ? Because when reading a line through input (), it is passed through an interpreter that converts the entered line into a command. Hands and itch to enter rm -rf ... Well, okay, drove on! The syntax of the function is this:

    login = raw_input("Enter your name: ")
    Here login is a variable into which the user-entered string is read after pressing Enter .
    Now let's open the file and write some information into it.

    gogo = open ("/home/username/helloworld","w")
    gogo.write("Hello, world!")
    gogo.close()


    By the way, I recommend checking, before you execute the above, did you have any necessary file in the address / home / username / helloworld ? And then, after all, everything in him will be erased and leave nothing at the scene of the crime, except for "Hello, world!"

    Well, now let's work directly with the console. Personally, I in one code fragment got the host address of my provider from issuing the host domen.com command . No sooner said than done. Wow, how much is ... Well, let's figure it out. Line by line. We connect standard python libraries for everything to work. os - a library for working with system calls and the console. re - for working with regular expressions.

    import os
    import re
    vid = os.popen("host l2tp.corbina.ru")
    re_dns = re.compile(r"([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)")
    for line in vid.readlines():
      hst=re_dns.search(line)
      if (hst != None):
        break
    host=hst.group(0)
    print "Corbina host adress is "+host




    import os
    import re



    vid = os.popen ("host l2tp.corbina.ru")
    Here we kind of “enter into the console” the command host l2tp.corbina.ru , and what we’ve got is stuffed into the vid variable as a list .

    re_dns=re.compile(r"([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)")
    This, my friends, is a regular expression conversion. re_dns is a variable into which a particular object is obtained using the re.compile () method . I won’t explain the regular expression syntax itself, especially since it is the simplest, I can only say that it is the simplest filter option for IP addresses.

    for line in vid.readlines():
    This starts the for loop. I think you have already noticed that in Python the syntax of the for loop is quite different from other languages. The line variable is taken here , into which the lines from the list are written in turnvid.readlines () . The lines in the list will end - the cycle will end. The colon at the end indicates the beginning of the section of statements that occur in the loop. These operators must be separated by tabs or a few spaces. As soon as we wrote everything that should happen in the loop, we simply write the next statement from the beginning of the line. By the way, this also applies to the conditional operator if , as seen below.

    hst=re_dns.search(line)
    And here we apply the previously received regular expression object to the line line , as a result of which either a list of matching lines is returned to hst , or None if nothing is found. Check for the same None . Pay attention again to the indent before

    if (hst != None):
      break

    break statement . As you probably know from other languages, this same break is a loop interrupt statement. Thus, as soon as hst becomes not equal to None , the cycle is interrupted.

    host=hst.group(0)
    As I said, a list of matching regular expression strings is returned to the hst variable . In fact, more precisely, the return is not a list, but a tuple of elements. And since we broke the loop as soon as we found the first suitable line, it will be written to the first (it is also zero) element of the tuple, which we safely get and write to host .

    print "Corbina host adress is "+host
    And then we display this IP address in the console. Print statementdisplays the string passed to it in the console, and even allows string concatenation by simple addition.

    Well, actually, that's all for a start. I’ll ask you especially not to scold or kick for the raggedness of the story, if there are any complaints - I will listen with pleasure and try to fix it.

    Also popular now: