How easy is it for people who can write linux commands in python to enter a big factory?

insert image description here

After reading this " 2000-word advice, for those who want to learn Python, it is recommended to collect it and read it carefully! "Readers should have a little impression of a command, right? Yes, it is the ls command that is often used in linux.

In the article, I mentioned how to improve my python ability? Directly find the project to write, but as a zero-based/novice/starter, you have to learn web frameworks, html, css, and js to start a blog, which has become an obstacle that hinders you from writing actual projects.

So I recommend this command: ls. Writing an ls is very simple, all you need is a little basic knowledge of linux and what ls can do.

So today, I will code a ls.py that can be used for everyone. Yes, windows can also be used~

demo environment

  • Operating system: windows10
  • python version: python 3.7
  • idea:pycharm 2018.2
  • Modules used: argparse, os

Understanding the argparse module

argparse is the standard library of python, it allows us to write a very friendly command line interface, and can automatically generate help documents and usage messages, and issue errors when the parameters are invalid.

argparse.ArgumentParse class parameter understanding

  1. prog: Change the name of the application, we can use %(prog)sthe name of the reference application, the default application name is the file name.
  2. usage: Display the usage of this command, generally used to display the usage of parameters
  3. description: Displays help information for this command
  4. epilog: display help information for the command, located below the parameters

argparse.ArgumentParser.add_argument function understanding

  1. name | flags: the name of the specified parameter
  2. action: Specify command line parameters, built-in as the following
    • store: The default value, only saves the parameter value.
    • store_const: Basically the same as store, but only saves the value specified by the const keyword, other values ​​will report an error
    • store_true | store_false: basically the same as store_const, only store True and False
    • append: save different values ​​of the same parameter in a list
    • count: count the number of occurrences of the parameter
    • help: print help information for the program
    • version: output program version information
  3. nargs: associates a different number of values ​​with a parameter
    • nargs=N: N is an integer
    • nargs = '?'
    • nargs='*': save all parameters in a list
    • nargs='+': save all parameters in a list, but at least one parameter
    • nargs=argparse.REMAINDER: The rest of the parameters are all stored in a list
  4. default: If this parameter is not passed in, the value of the default parameter is used by default
  5. type: The received parameter will be processed by the function corresponding to this parameter.
  6. choices: Specify the parameters within a range, and an error will be reported if the parameters are exceeded
  7. required: Specifies whether the parameter is a required parameter.
  8. dest: The name of the custom parameter, the default name is "value after -" or "value after --".

Scripting the ls command

Here we simply specify three parameters.

  • -a: Add the -a parameter to show hidden files.
  • -r: Add the -r parameter to recursively display the files under the folder.
  • -d: Specify the display directory, if not specified, the default is the current directory.

First we use the ArgumentParser class to specify the 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 specify the parameters, the next step is to implement the specific ls. We encapsulate a LsCommand class

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

We have also encapsulated the ls class. Next, we will pass the obtained parameters into the LsCommand class, and then run it, we can get the result happily.

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

Show results:

python ls.pyinsert image description here

python ls.py -ainsert image description here

python ls.py -a -rinsert image description here

python ls.py -d ./tempinsert image description here

Follow the official account " Python Column " and reply to " Machine Learning E-books " in the background to get 100 machine learning e-books for free

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324129762&siteId=291194637