Python module (cross-directory) call summary

System module call

Speaking of module invocation, everyone should have a basic understanding of import. It is very common in projects such as import time, from selenium import webdriver, etc. We often use the syntax of from...import.../import... in python to quote some System module, after importing the system module, you can call the methods defined in the module, for example:

from time import ctime

print ctime()

import time


The ultimate purpose of print time.ctime() is to obtain and print the current time.

In method one, by introducing the time module and importing the ctime method below it, the call to the ctime() method is realized. Because from is used, the specific ctime method that needs to be called is specified. When using it, directly write the method name ctime( ) Can be called,

In the second method, the entire time module is directly introduced. When using it, you need to add the module name and then reference time.ctime() in the following methods.

Custom module call

When we are coding and designing, we often need to customize some modules. Other programs can call these modules. Then the method and principle are similar to the above system module calls. Let us give a chestnut:

First create a directory ModPython, and define a public module PublicA.py below. For a better understanding, I am a chestnut of simple methods written.

#PublicA.py
def PubA():
print "I'm PublicA in /ModPythonh/PublicA.py"
Next, create a new python program A.py in this directory to call this custom module

#A.py
import PublicA
PublicA.PubA()
The results of running A.py are as follows:

I am def PubA_1 in /ModPythonh/PublicA.py
[Finished in 1.1s]
As a result, the PubA() method in PublicA.py was successfully printed, indicating that the call was successful~

Let's take a look at the directory structure just now, because the two scripts PublicA and A are both in ModPython, so just use import to quote them directly:

ModPython/

-------------/ PublicA.py

------------- / A.py

At this time, if we create a new folder B in the ModPython project, create a new file b1.py and b2.py, the directory and specific contents are as follows:

ModPython/

-------------/ PublicA.py

------------- / A.py

-------------/B

-------------/B                  /b1.py

-------------/B                  /b2.py

#b1.py
def b1_1():
print “I am def b1_1 in /ModPythonh/B/b1.py”

def b1_2():
print “I am def b1_2 in /ModPythonh/B/b1.py”
#b2.py
def b2_1():
print “I am def b2_1 in /ModPythonh/B/b2.py”

def b2_2():
print "I am def b2_2 in /ModPythonh/B/b2.py" At
this time, we import b1 in A.py, and then b1.b1_1(), try if it succeeds...

An error was reported at this time: ImportError: No module named b1, it said that there is no module named b1. Why? Because b1 and the executable program A.py are not in the same directory, they can’t be found. How to solve this time? (Knock on the blackboard (o゚v゚)ノ) Please see the key points...

Python cross-directory module call

Continue to use the directories that have been created above, and then continue to click on more complex ones according to the following rules. After the completion, we will talk about the cross-directory module calls in different situations in turn...

-------------/A.py
-------------/PublicA.py
-------------/B /b1.py
-------------/B /b2.py
-------------/C /c.py

Create a folder C in ModPython, and create a new c.py file in it. Once the file is built, let's talk about it separately.

Sub-file call in the same level directory

In our file structure, there are PublicA.py and B and C directories at the same level as A.py, so for A.py, b1, b2, and c are sub-files.

If we want to call b1 in A.py, what do we need to do?

If you import b1 directly, an error will be reported after the interview, and module b1 cannot be found because b1 and A are no longer in the same directory.

Then we find the parent directory B of b1, B and A.py are in the same directory, B as a module, b1 and b2 are called as methods in the module, in order to let the system know that B is a module, we You need to create a new file called __init__.py under B. The content can be empty. This file can tell python B is a callable module.

-------------/B /init.py

After it is built, we will call and execute it in A.py:

from B import b1,b2
b1.b1_1()
b2.b2_2()
operation result:

I am def b1_1 in /ModPythonh/B/b1.py

I am def b2_2 in /ModPythonh/B/b2.py
so there is no problem, let's add that the other two writing methods are also possible:

#A.py
from B.b1 import *
b1_1()
#A.py
import B.b1
B.b1.b1_1() The
above three methods are based on the __init__.py file is empty, I personally prefer The first one, but the problem is, if there are many files under B, I may need a different method each time I call it, can I write it directly every time I call it:

from B import *

b1.b1_1()
b2.b2_2()
We can try to execute it to see if it works, this time it prompts: NameError: name'b1 ' is not defined, if you want to directly introduce B below each time you execute the call For all modules, we need to add and import in the __init__.py file:

# init .py
import b1,b2
so that you can write import * directly.

Cross-module calls between directories at the same level

ModPython
---------/A.py
---------/PublicA.py
---------/B /init.py
---------/B /b1.py
---------/B /b2.py

---------/C /c.py

Let's look at this directory structure again and sort it out. For B and C, they are at the same level, and b1 and c are also at the same level. What should we do if we need to call b in c? If called by A.py before, there will still be this familiar error: ImportError: No module named B, the imported module is B, and the B and c.py files are not in the same directory, if needed. Call, then go back to the upper-level directory C, and then start from B import b1

To jump to the directory, we need to call the python sys module to implement it. The specific implementation method is as follows:

#c.py
import sys
sys.path.append(’…’)
from B import b1

b1.b1_1()
uses append() method to append, ... means going back to the previous directory.

Let’s look at our chestnut again. When c.py returns to the upper level, it is the C directory. For C, it is the same level as B. The __init__.py file has been created under B, which is already a module that can be used to import At this time, from B import b1 can be called smoothly without any problem.

Knowing this, the problem of python cross-directory calling custom modules has basically been solved. It really doesn't work. There is a universal method (smile(/▽\)):

Just create the __init__.py file in the folder to which the called file belongs, then import the sys module, and directly write the absolute path of the file to be called when appending with append.

For example, above, we want to call the file in B, only need to find the absolute path of B, assuming it is C:\Users\ModPython\B, then append is written like this:

sys.path.append('C:\Users\ModPython')
So no matter what the situation, you can find it~~~~

A little understanding about .pyc files

Since the aforementioned various operational definition module called, before the new directory if one more look back, I believe not difficult to find a few more .pyc files, such as the above b1.pyc, the init .pyc, Why are these pyc files generated, and what is the role of pyc files? I have checked some information and talked about my understanding here.

First, let's take a look at the steps of python's operation and compilation mechanism:

Python operation naturally depends on the interpreter, which converts the python source code into bytecode, and then executes the converted bytecode.

So when we are introducing and calling some modules...

During the module loading process, the source code is translated into a PyCodeObject object (that is, bytecode) by the virtual machine (interpreter).
The PyCodeObject is written to the CPU, and the next run will read instructions directly from the memory and execute the program
. After the end, according to the execution method, decide whether to write the execution result back to the hard disk, that is, copy it to the .pyc file.
When executing again, first check whether there is a .pyc file, if so, then check the bytecode file and itself If the modification time is the same, run the .pyc file directly if the modification time is the same, and re-execute the previous three steps if it is inconsistent or there is no bytecode file.
Therefore, all the modules we called earlier generate a .pyc file.

From the analysis of the above steps, it can be seen that the .pyc file is relative to the .py file. Since it is executed and written into the memory space, the loading speed will be faster than that of the .py file, which can speed up the running of the program.

Of course, since the execution of .pyc and .py are the same, .py is directly presented in the form of source code, and .pyc is just a bytecode file. To some extent, it can also prevent the code from being peeked. Has a certain hidden effect...
————————————————
Copyright statement: This article is the original article of the CSDN blogger "My pig is very powerful", following the copyright of CC 4.0 BY-SA Agreement, please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/qq_32897143/article/details/79960432

Guess you like

Origin blog.csdn.net/Love_Polaris/article/details/106682534