Python learning journey: a Python in Linux ls command

I, EDITORIAL

  A few days ago to see on the micro-channel such an article, the link is: https://mp.weixin.qq.com/s/rl6Sgv3uk_IpoFAx6cWa8w , in this article, there is a quote that caught my attention:

  

   In Linux ls is a very high frequency of command, the optional parameters, there are many, have to be regarded as a master of command. Python as a language easy to learn, considered by many to seriously study is not needed, or just whatever tune a database on the line, it may really look down upon the Python. Well, this time I will try to achieve what Python in Linux ls command, little to prove at Python's simple!

 

Two, ls Introduction

  Linux ls command to specify the contents of the working directory for display. The syntax is as follows:

ls [-alkrt] [name]

  Just to name a few common parameters, optional parameters of the ls command or a lot, you can use man ls to view specific information. Several parameters listed here correspond to the following meanings:

  1) -a: shows all files and directories;

  2) -l: In addition to the file name, file size will also create time and other information are listed;

  3) -k: KB file size expressed in form;

  4) -r: the files are sorted in the reverse order;

  5) -t: file to modify the time sequence arrangement.

 

Third, specific ideas

  The main module is used and argparse os, can be provided and wherein the module receiving argparse command line parameters, also so that the operation of the Python command line becomes simple, and os module is used for file operation, for argparse module may be unfamiliar here to see the official documentation.

  Since the use Python implementation ls.py, also will be carried out in the command line operations, such as python ls.py -a such an order, while Python familiar people might think of using the sys module to receive input commands, but use argparse make the command line easier! First of all you want to import the module and create a ArgumentParser objects, it can be understood as a parser, then you can use add_argument () method for the parser to add a parameter. Examples are as follows:

 1 # test.py
 2 import argparse
 3 
 4 parser = argparse.ArgumentParser(description='Find the maximum number.')
 5 parser.add_argument("integers", type=int, nargs="+", help="The input integers.")
 6 parser.add_argument("-min", nargs="?", required=False, dest="find_num", default=max, const=min, 
 7                     help="Find the minimum number(Default: find the maximum number).")
 8 
 9 
10 args = parser.parse_args()
11 print(args)
12 print(args.find_num(args.Nums))

  Function code is inputted into a plurality of integers, wherein the default maximum demand, if the parameter is for the minimum -min therein. You can see when you create a parser and add the command line parameters are set description description information, this information will be displayed when we use the --help command, for example:

  

  In the above code, to be noted that where add_argument () adds a location parameter "integers" and an optional parameter "-min", position parameter must be present in the command line, is not missing, it is not required provided parameters, while the optional parameter is not a must have, and therefore can also use the default parameter settings default. Nargs parameter sets the number of command line arguments, "+" means one or more, "?" Denotes zero or one, here due to the digital input may have more, so be set to "+." Ultimately run the sample as follows:

> python test.py 1 3 5

Namespace(find_num=<built-in function max>, integers=[1, 3, 5])
5

> Python test.py 1:03 a.m. 5 -min

Namespace(find_num=<built-in function min>, integers=[1, 3, 5])

1

  About argparse ends here, the following is a brief module os, os module provides a convenient way to use the operating system-related functions, the method in this module are used comprising ls.py achieved:

  1) os.path.isdir (path): If the path is an existing directory, returns True.

  2) os.listdir (path): returns a list, including the contents corresponding directory path, and does not include "..", even if they exist. "."

  3) os.stat (path): Get File file descriptor or a state, returns a stat_result objects, which contains various status information.

 

Fourth, the main code

   Ls.py main function is as follows, the main function is to create a parser, and a position setting the optional parameter, then the received command line parameter information, and calls the appropriate method in accordance with the input parameters, there is provided a "-V" parameter displays the version information, you can use the "-V" or "-Version" view.

. 1  DEF main ():
 2      "" " 
. 3      main functions, settings, and receive command line arguments, and calls the corresponding method according to the parameter
 . 4      : return:
 . 5      " "" 
. 6      # create the parser 
. 7      the parse = argparse.ArgumentParser (Description = " Python_ls " )
 . 8      # optional parameters 
. 9      parse.add_argument ( " -a " , " -all " , = Help " the Show All Files " , Action = " store_true " , required = False)
 10      the parse.add_argument("-l", "-long", help="View in long format", action="store_true", required=False)
11     parse.add_argument("-k", help="Expressed in bytes", action="store_true", required=False)
12     parse.add_argument("-r", "-reverse", help="In reverse order", action="store_true", required=False)
13     parse.add_argument("-t", help="Sort by modified time", action="store_true", required=False)
14     parse.add_argument("-V", "-Version", help="Get the version", action="store_true", required=False)
15     # 位置参数
16     parse.add_argument("path", type=str, help="The path", nargs="?")
17 
18     # 命令行参数信息
19     data = vars(parse.parse_args())
20     assert type(data) == dict
21     if data["V"]:
22         print("Python_ls version: 1.0")
23         return
24     else:
25         check_arg(data)

   Then is a function of obtaining content information in the specified path, the path to do is determine whether there is, if there is a return to the file list, if there is an error message is displayed, and exit the program.

. 1  DEF get_all (path):
 2      "" " 
. 3      acquires the entire contents of the specified path
 . 4      : param path: Path
 . 5      : return:
 . 6      " "" 
. 7      IF os.path.isdir (path):
 . 8          Files = [ " . " , " .. " ] + the os.listdir (path)
 . 9          return Files
 10      the else :
 . 11          Print ( " No SUCH File or Directory " )
 12 is          Exit ()

 

6.3.5 Operating results

  The following is a partial screenshot of the results of the operation ls.py.

  First python ls.py -a, and there is no input path, i.e. uses the default path to the current directory, as shown below:

  

  Then the python ls.py -a -t, use this command displays all the contents of the current directory, sorted according to the time of creation, as shown below:

  

  Finally, python ls.py -a -l -k -r, but also display all the contents of the current directory and create a name in accordance with the order, but the file size in KB to display, as shown below:

  

   Up to this point, ls.py even if it is basically achieved, of course, there are many features you can go to achieve, such as more parameters, etc., if you are interested, then you can try it yourself ==

 

  The complete code has been uploaded to GitHub !

Guess you like

Origin www.cnblogs.com/TM0831/p/11459109.html