Linux commands will use python to write again people, easy to get into how manufacturers?

Here Insert Picture Description

Read this " after 2000 word admonition, for those who want to learn Python, the proposed collection look! "Readers should have a command of a little impression, right? Yes, that is often used in linux ls command.

The article I mentioned how to enhance their ability to do python? Write directly to the project, but as a zero-based / white / entry you have to learn is to do a blog web framework, html, css, js, has become a hinder you write the actual project obstacles.

So I would recommend this command: ls. Ls write a very simple, just the basics you'll need a bit of linux, ls know what to do just fine.

Well, today we give a code Nana usable ls.py, yes, windows can be oh ~

Demo environment

  • Operating System: windows10
  • python version: python 3.7
  • idea:pycharm 2018.2
  • Use Module: argparse, os

Learn argparse module

argparse is python standard library, he allows us to write very friendly command line interface, and can automatically generate help files and using the message, but also send the wrong time in an invalid parameter.

argparse.ArgumentParse class parameter understand

  1. prog: change the name of the application, we can use the %(prog)sname refers to the application, the default application name for the file name.
  2. usage: displays the command usage, generally used to display the usage parameters
  3. description: This command displays help information
  4. epilog: The following display help information, the location of the command parameters

argparse.ArgumentParser.add_argument understand the function

  1. name | flags: the name of the specified parameters
  2. action: specify command-line parameters built into the following
    • store: defaults, save only parameter values.
    • store_const: basically the same store, but only to save the const keyword specified value, the other value will complain
    • store_true | store_false: consistent with store_const, save only the True and False
    • append: The different values ​​of the same parameter stored in a list in
    • count: the number of statistical parameters appear
    • Help output of the program: help
    • version: output version information
  3. nargs: associating a different number with a value of the parameter
    • nargs = N: N is an integer
    • narges = "?"
    • nargs = '*': all parameters stored in the list
    • nargs = '+': all parameters stored in the list, but must have at least one parameter
    • nargs = argparse.REMAINDER: All the remaining parameters are stored in a list
  4. default: If you do not pass this parameter, the default values ​​using the default parameters
  5. type: the received parameter processing pass this parameter corresponding to the function.
  6. choices: the parameter specifies a range beyond it given
  7. required: Specifies whether the parameter is mandatory pass parameters.
  8. dest: the parameter name of the custom default name "- the latter value" or "- the value of the back."

Ls command script writing

Here we simply specify three parameters.

  • -a: add -a parameter, show hidden files.
  • -r: the -r parameter, folders recursively display the following file.
  • -d: specifies the directory display, if not specified, the default is the current directory.

First, we use ArgumentParser class to specify parameters.

import os
import argparse

parser = argparse.ArgumentParser(prog='ls', description='显示文件夹下的文件')

# 指定参数
parser.add_argument('-a', '--all', const=True, nargs='?', help='是否显示隐藏文件')
parser.add_argument('-d', '--directory', help='指定显示的目录,如果不指定,默认为当前目录')
parser.add_argument('-r', '--recursion', const=True, nargs='?', help='是否递归显示')

# 解析参数
args = parser.parse_args()

# 拿到directory参数,如果没有传这个参数,为None
directory = args.directory
# 如果directory有值
if directory:
    # 如果指定目录不存在,抛出异常
    if not os.path.exists(directory):
        raise ValueError(f'{directory} does`t exist')

    # 如果directory不是一个目录,抛出异常
    if not os.path.isdir(directory):
        raise ValueError(f'{directory} is not a directory')

# 如果directory为None,给directory赋值
else:
    directory = '.'

After we set up parameters, the next step is to achieve concrete ls. We package a class LsCommand

class LsCommand():
    def __init__(self, show_all=False, directory='.', recursion=False):
        '''
        :param show_all: 是否显示隐藏文件
        :param directory: 指定的文件目录
        :param recursion: 是否递归显示目录下的文件
        '''
        self.show_all = show_all
        self.recursion = recursion
        self.directory = os.path.abspath(directory)


    def handle_dir(self, directory, grade=1, placeholder='--'):
        '''
        处理目录
        :param directory: 文件目录
        :param grade: 目录层级
        :param placeholder: 子目录文件前面的占位符
        :return:
        '''
        # 判断是否为文件夹

        # grade是否增加过了

        # os.listdir: 列出当前文件夹下面的所有文件和文件夹
        # 遍历目录下的文件,文件夹
        pass

    def show_file_or_dir(self, file, prefix=''):
        # 如果不显示隐藏文件

        # 打印前缀和文件名
        pass

    def run(self):
        '''
        运行ls命令
        :return:
        '''
        # os.listdir(dir) 得到dir目录下所有文件,文件夹

        # 遍历self.directory目录先所有文件,文件夹

        pass

ls this class we have a good package, then we will get the parameters passed LsCommand class, and then run, the outcome can be enjoyable.

ls = LsCommand(bool(args.all), directory, bool(args.recursion))
ls.run()

Show results:

python ls.py
Here Insert Picture Description

python ls.py -a
Here Insert Picture Description

python ls.py -a -r
Here Insert Picture Description

python ls.py -d ./temp
Here Insert Picture Description

No public concern " Python column ," replies back " machine learning eBook " free access to 100 e-books Machine Learning

Guess you like

Origin www.cnblogs.com/moonhmily/p/11565918.html