Iron python_day28_ Module Learning 3

Source: Internet
Author: User
Tags define function function definition

Most of the content is excerpted from the instructor's blog http://www.cnblogs.com/Eva-J/

OS Module review one or two

>>> ImportOs>>>OS.GETCWD ()# Get the current directory' d:\\portablesoft\\python35 '>>>Os.chdir (' d:\\Portablesoft ')# Change Working directory, equivalent to CD command>>>OS.GETCWD ()' D:\\portablesoft '>>>Os.curdir# get '. ' String, equivalent to the current directory'. '>>>Os.pardir# get ' ... ' String, equivalent to ancestor (parent directory) directory' ... '>>> ImportOs>>>Os.sep' \ \ '>>>Os.linesep' \ r \ n '>>>Os.pathsep'; '>>>Os.name' NT 'Os.system (' dir ')# Just run the order rightPrint(Os.popen (' dir '). Read ())# The output that executes has a return valueThe volume in drive E is the serial number of the VM volume is 4ae6-716D E:\Python\Directory of Day282018-04-25   -: +    <DIR>.2018-04-25   -: +    <DIR>..2018-04-25   -: One                 4New.txt2018-04-25   -: +               323OS module. py2A file327Bytes2List of +,048,944, -Available bytes

Print(Os.path)# <module ' Ntpath ' from ' d:\\portablesoft\\python35\\lib\\ntpath.py ' >Print(Os.path.abspath (Os.curdir))# E:\Python\day28Print(Os.path.split (' E:\Python\day28 '))# (' E:\\python ', ' day28 ')Print(Os.path.abspath (Os.pardir))# E:\PythonPrint(Os.path.dirname (' E:\Python\day28 '))# E:\PythonPrint(Os.path.basename (' E:\Python\day28 '))# day28Print(Os.path.exists (' E:\Python\day28 '))# TruePrint(Os.path.exists (' E:\Python\day29 '))# FalsePrint(Os.path.join (' E:\Python ',' day28 ',' OS module. PY '))# E:\Python\day28\OS module. PYPrint(Os.path.getmtime (' E:\Python\day28 '))# 1524649925.9140468 Gets the time stamp, so you also need to go to the time to format the stringRes=Os.path.getmtime (' E:\Python\day28 ')Print(Time.strftime ('%y-%m-%d %x', Time.gmtime (res)))# 2018-04-25 09:57:58
Add: Os.walkos.walk Enter a path name in the form of yield (actually a generator) to return a ternary group Dirpath, Dirnames, filenames example: Print output directory treeImportOsdefTraveltree (Currentpath, Count):" "recursively display file directories in a tree-like manner:p Aram Currentpath: directory path to display:p Aram Count: The directory hierarchy to display: Return: No returned value, direct recursive printout formatted file tree" "    # To determine that the incoming path does not exist, there is no direct return to none    if  notOs.path.exists (Currentpath):return    # Determine if the incoming path is a file    ifOs.path.isfile (Currentpath):# is the file returns the filenameFileName=Os.path.basename (Currentpath)# Print output defined level tab stitching tree symbol plus filename        Print('\ t' *Count+ ' ├── ' +FileName)# When the path is a directory    elifOs.path.isdir (Currentpath):# Print output defined level tab stitching tree symbol plus directory path        Print('\ t' *Count+ ' ├── ' +Currentpath)# Put the table of contents in a listPathList=Os.listdir (Currentpath)# for Loop and recursively repeats the previous action         forEachpathinchPathlist:traveltree (Currentpath+ '/' +Eachpath, Count+ 1)
What is a module?

Common scenario: A module is a file that contains Python definitions and declarations, and the file name is the suffix of the module name plus the. Py.
In fact, the import loaded module is divided into four general categories:
1 code written using Python (. py file)
2 C or C + + extensions that have been compiled as shared libraries or DLLs
3 packages for a set of modules
4 built-in modules written and linked to the Python interpreter using C

Why use a module?

If you quit the Python interpreter and then re-enter, then the functions or variables you defined previously will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.

With the development of the program, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. At this point, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the reuse of functionality.

A module can contain definitions of executable statements and functions that are intended to initialize modules that execute only when the module name is first encountered when importing an import statement (the import statement can be used anywhere in the program and is imported multiple times for the same module. To prevent you from repeating the import, Python is optimized by loading the module name into memory after the first import, followed by an import statement that only adds a reference to the module object that has loaded the large memory, and does not re-execute the statements within the module.

We can find the module that is currently loaded from Sys.modules, Sys.modules is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.

Each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our own module in the definition of global variables will be imported, and the user's global variables conflict.

Summary: Three things to do when importing a module for the first time:

1. Create a new namespace for the source file (the imported module module), which is the namespace that is accessed when the functions and methods defined are used in global.
2. Execute the code contained in the module in the newly created namespace;

What exactly did you do when you imported the module?
In fact function definitions is also ' statements ' that is ' executed '; The execution of a Module-level function definition enters the function name in the module ' s global symbol table.
In fact, function definitions are also "executed" statements, and the execution of module-level function definitions puts function names into the module global namespace table, which can be viewed with globals ().

3. Create a name to reference the namespace with the imported module name
There is no difference between this name and the variable name, it is ' first class ', and the name defined in the Py file can be accessed by using the imported module name, and the name of the. Name in the file is from two completely different places.

Alias the module:

Alias for module name, equivalent to Json=seq;pickle=seq

Demonstration Usage One:
There are two SQL modules MySQL and Oracle, depending on the user's input, choose different SQL functions

#mysql. PYdefSqlparse ():Print(' from MySQL sqlparse ')#oracle. PYdefSqlparse ():Print(' from Oracle Sqlparse ')#test. PYDb_type=input(' >>: ')ifDb_type== ' MySQL ':ImportMysql asDbelifDb_type== ' Oracle ':ImportOracle asDbdb.sqlparse () Demonstration Usage II: The way to alias an imported module is useful for writing extensible code, assuming there are two modules xmlreader.py and csvreader.py, which define function read_data (filename): Used to read some data from a file, but with a different input format. You can write code to selectively select read modules, such asifFile_format== ' xml ':ImportXmlReader asReaderelifFile_format== ' CSV ':ImportCsvreader asReaderdata=Reader.read_date (filename) from...Import... Comparing import My_module, the name space of the source file will be' My_module 'To the current namespace, which must be my_module. The way the name is used. The FROM statement is equivalent to import, and a new namespace is created, but the from is imported directly into the current namespace in the My_module, and the name is used directly in the current namespace. Example: From MathImportPi is a good way to use PI directly in the current position, and still go back to the math file global namespace to look for the name Pi. One particular point to emphasize is that variable assignment in Python is not a storage operation, but a binding relationship. From is also supported as, alias. Other than that fromMy_moduleImport *All names in My_module that are not preceded by an underscore (_) are imported into the current location, and in most cases our Python program should not use this type of import because*You don't know what name you import, it's likely to overwrite the name you've defined before. And the readability is extremely poor, there is no problem when importing in an interactive environment. Add a line __all__ in my_module.py=[' Money ',' Read1 ']#这样在另外一个文件中用from My_module Import * Imports the two names specified in the list. 
Loading and modification of modules

For performance reasons, each module is imported only once and placed in the dictionary sys.modules,
If you change the contents of the module, you must restart the program, Python does not support reloading or uninstalling the previously imported modules,
Some students may think of removing a module directly from the Sys.modules can not be uninstalled,
Note that you deleted the module object in the Sys.modules can still be referenced by the components of other programs, so it will not be erased.
In particular, we refer to a class in this module, which produces many objects with this class, so that these objects have references to this module.

If it's just a module that you want to test interactively, use importlib.Reload(), e.g.ImportImportlib;Importlib.Reload(ModuleName), which can only be used for test environments. Take the module as a script we can view the module name by using the global variable __name__ of the module: Run as a script:__name__Equals' __main__ 'Import as module:__name__=Module name function: Used to control the. py file to perform different logic under different application scenariosif __name__ == ' __main__ ': module search path The Python interpreter automatically loads some modules at startup and can be viewed using sys.modules. When a module is imported for the first time (such as My_module), it is first checked to see if the module has been loaded into memory (the memory that corresponds to the current execution file's namespace), if any, and if not, the interpreter looks for the built-in module with the same name. If you haven't found it, look for the my_module.py file in the list of directories given by Sys.path. So the search order of the summary module is: The module that has been loaded in memory -Built-in Modules -The module that is contained in the Sys.path path. The value of Sys.path initialization is from: The directory containing theinputScript (orThe current directory when nofile  isSpecified). PYTHONPATH (AListof directory names, withThe same syntax asThe shell variable PATH). The installation-Dependent default. It is important to note that our custom module names should not be the same as the system's built-in modules. Although it is said every time, there will still be people who make mistakes. After initialization, the Python program can modify the Sys.path, and the path is placed prior to the standard library being loaded.1 >>> ImportSys2 >>>Sys.path.append ('/A/B/C/D ')3 >>>Sys.path.insert (0,'/x/y/z ')#排在前的目录, priority to be searchedNote: The search is based on the left-to-right order in Sys.path, the first priority is found, the Sys.path may also contain. zip archive files and. egg files, and Python will treat. zip archives as a directory. As for the. Egg file is a package created by Setuptools, which is a common format used in accordance with third-party Python libraries and extensions, and. Egg files are really just. zip files that add additional metadata such as version numbers, dependencies, and so on. One thing to emphasize is that you can only import. py,.pyc files from a. zip file. Shared libraries and extension blocks written using C cannot be loaded directly from the. zip file (at this point the packaging system such as setuptools can sometimes provide a workaround), and loading files from. zip does not create. pyc or. pyo files, so be sure to create them beforehand to avoid loading modules that are degraded by performance.

Website Link: Https://docs.python.org/3/tutorial/modules.html#the-module-search-path
Search Path:
When a module named My_module is imported, the interpreter first looks for the name from the built-in module, and then goes to Sys.path to find the name.

The Sys.path is initialized from the following location:

1) The current directory where the execution file resides
2) Ptyhonpath (contains a list of directory names, like the shell variable path syntax)
3) dependent on the default specified during installation

Note: In a file system that supports soft connections, the directory in which the script is executed is computed after the soft link.
In other words, a directory containing soft links is not added to the module's search path.

After initialization, we can also modify the Sys.path in the Python program, the path where the executable file is located is the first directory of Sys.path,
In front of all standard library paths. This means that the current directory takes precedence over the standard library directory,
It should be emphasized that our custom module name does not duplicate the module name of the Python standard library.

End
2018-4-27

Iron python_day28_ Module Learning 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.