You've seen this book 2000 words of admonition, for those who want to learn Python, I suggest you look after your collection! Should all readers of the book be a little impressed by a command?Yes, it is the ls command that is often used in linux.
I mentioned how to improve my python capabilities in this article?Find projects to write directly, but as a zero-base/whitespace/starter, blogging with web frameworks, html, css, js is another obstacle that prevents you from writing actual projects.
So I recommend this command: ls.Writing an LS is very simple. You just need a little bit of linux basics to know what LS can do.
So today I'll give you a code on how to use ls.py. That's right. windows is OK.
Demonstration environment
- Operating system: windows10
- python version: python 3.7
- idea: pycharm 2018.2
- Use module: argparse, os
Understanding the argparse module
argparse is python's standard library, which allows us to write a command-line interface friendly, generate help documents and usage messages automatically, and issue errors when parameters are invalid.
Understanding argparse.ArgumentParse class parameters
- Prog: To change the name of the application, we can use%(prog)s to reference the name of the application. The default application name is the file name.
- Usage: Displays this command usage, typically used to display parameters
- description: Displays help information for this command
- epilog: Displays help information for the command, located below the parameters
Understanding the argparse.ArgumentParser.add_argument function
- name | flags: Name of the specified parameter
- action: Specifies command line parameters, built-in as follows
- store: Default value, only parameter values are saved.
- store_const: Almost identical to store, but only the value specified by the const keyword will be saved, other values will fail
- store_true | store_false: Much like store_const, only True and False are saved
- append: Save different values of the same parameter in a list
- count: Number of occurrences of statistical parameters
- Help:Output program help information
- Version: Output program version information
- nargs: Associate a different number of values with a parameter
- nargs=N:N is an integer
- nargs='?'
- nargs='*': Save all parameters in the list
- nargs='+': Save all parameters in the list, but at least one parameter is required
- nargs=argparse.REMAINDER: All remaining parameters are saved in a list
- Default: If this parameter is not passed in, the default parameter value is used by default
- type: The received parameter is processed by the function corresponding to this parameter.
- choices: Specify parameters in a range, error if exceeded
- Required: Specifies whether the parameter is required.
- dest: Name of the custom parameter, default name is'-followed by value'or'--followed by value'.
Scripting ls commands
Here we simply specify three parameters.
- -a: Add-a parameter to show hidden files.
- -r: Add the-r parameter to recursively display the files under the folder.
- -d: Specifies the display directory, if not, defaults to the current directory.
First, we use the ArgumentParser class to specify parameters.
import os import argparse parser = argparse.ArgumentParser(prog='ls', description='Show files under folders') # Specify parameters parser.add_argument('-a', '--all', const=True, nargs='?', help='Whether to show hidden files') parser.add_argument('-d', '--directory', help='Specifies the directory to display, if not specified, defaults to the current directory') parser.add_argument('-r', '--recursion', const=True, nargs='?', help='Whether to show recursively') # Parsing parameters args = parser.parse_args() # Get the directory parameter, if it's not passed, it's None directory = args.directory # If directory has value if directory: # Throw an exception if the specified directory does not exist if not os.path.exists(directory): raise ValueError(f'{directory} does`t exist') # Throw an exception if directory is not a directory if not os.path.isdir(directory): raise ValueError(f'{directory} is not a directory') # Assign a value to directory if directory is None else: directory = '.'
Once we have defined the parameters, the next step is to implement the specific ls.We encapsulate an LsCommand class
class LsCommand(): def __init__(self, show_all=False, directory='.', recursion=False): ''' :param show_all: Whether to show hidden files :param directory: Specified File Directory :param recursion: Whether to display files in directories recursively ''' self.show_all = show_all self.recursion = recursion self.directory = os.path.abspath(directory) def handle_dir(self, directory, grade=1, placeholder='--'): ''' //Processing Directory :param directory: File directory :param grade: Catalog hierarchy :param placeholder: Placeholder before subdirectory file :return: ''' # Determine whether it is a folder # Has grade increased # os.listdir: List all files and folders under the current folder # Traverse files, folders under directories pass def show_file_or_dir(self, file, prefix=''): # If hidden files are not displayed # Print prefix and file name pass def run(self): ''' //Run ls command :return: ''' # os.listdir(dir) gets all the files, folders in the dir directory # Traverse the self.directory directory first all files, folders pass
The ls class is also encapsulated. Next we pass the parameters into the LsCommand class and run them to get a pleasant result.
ls = LsCommand(bool(args.all), directory, bool(args.recursion)) ls.run()
Effect display:
python ls.py
python ls.py -a
python ls.py -a -r
python ls.py -d ./temp
Focus on the public number "Python Column". Reply back to "Machine Learning E-Book" to get 100 free Machine Learning E-books