Python + Selenium: Thread module encapsulationCollect results from threads.[SE12]
by - Thursday, January 1, 1970 at 12:00 AM
In the course "Python + selenium: encapsulating selenium with threads. [se10]", we have a preliminary understanding from the perspective of "novice"__ init__ Constructor
Then, we briefly introduce the process of PE loading binary executable programs.

Moreover, I emphasized that "do not try to modify the variables in the main process within the thread without fully understanding the working principle of the thread".
Here, you may have questions, why?

Well, before collecting the results, let's think about this issue from the perspective of "novices".

After PE loads the executable program, we know that memory space will be allocated for the variables that have been initialized.

So, what about the function? (for example, methods in our class objects)
Are they initialized?
Have you allocated memory space?

Then, as a simple understanding, I will tell you (for example, the input_account function in our course) that there is no memory space allocated.

what? It's strange. Yes, here you should remember that these functions (class methods) are allocated memory space only when the program is running.

Where is the allocation? The answer is to allocate to the stack.
When the program runs, the computer will allocate a "table" for these functions according to the "PE loading rules". This table records the information of these functions in memory.

So please use the "novice angle" to remember here: when the program runs to this function, memory space is allocated, and it is allocated in the stack. When the program ends, the stack will be released.
You will ask, why were they released?
Answer: for stack balance, the program applies for stack space for this function before running this function. When the stack space is used up, the stack space will be returned to the system.

After remembering the above keywords, we have a foundation for the following things to remember:
1. This is why function variables have "scope":
Because the local variables defined in the function are allocated to the stack space. Each local variable will also have a memory address at this time.
After the function is executed, these spaces are released. What problems will occur when you access the variables (memory addresses) in the old stack space?

2. Yes, this is the "wild pointer" called in strongly typed languages such as C and C + +. Because it is released, if you are lucky, you will access the old value. If you are not lucky, you will access the "unexpected data".
Well, at this time, your program is like a bomb, which will explode at any time.
Therefore, this is why it is emphasized that when using strong type programming languages such as C and C + +, a good habit should be formed. The memory space should be initialized before use and erased and released after use.
Fortunately, in Python, we don't need to care about these issues, because Python is very friendly, and it has completed relevant operations for us when we operate functions.
Well, having said so much, I just want to emphasize again the issue of "thread safety" mentioned in the previous lesson. This problem exists in the mutual access between "threads and threads" and "processes and threads".
So, at this point, the problem seems to have fallen into a dead circle?
Is there any way to safely use threads? After all, I just want to get the results in the business logic thread. It's too nagging!
Forgive me for saying so much

OK, with the above basic concepts, let's take a simple example:

Thread_Get_Result.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 2022-08-25
# Breached.to Bullet Class: mejuri Project
# THE FAST ONLINE VERSION 1.0CB

# Import thread from threading standard library
from threading import Thread

# We pretend to create a "business class":
# Why? Because we plan to encapsulate the business logic into modules and then use threads to execute
class SeleniumLogicMethods(Thread):

    def __init__(self, account_info):
        super(SeleniumLogicMethods, self).__init__()
        self.AC_INFO = account_info

        # Define a result: default False
        self.result_TaskDict = {"result": False}

    def run(self):
        print("Attack account:{} password:{}".format(self.AC_INFO['account_name'], self.AC_INFO['acccount_password']))

        # Suppose a result:
        _tmp_Result = True
        if _tmp_Result:
            # If the result meets the expected value: Set the value of "self.result_TaskDict"
            self.result_TaskDict = {"result": True}

    def Get_Result(self):
        """
        Return result
        :return:
        """
        try:
            return self.result_TaskDict
        except Exception:
            return self.result_TaskDict


if __name__ == '__main__':
    # Create a list. Suppose this is the account list
    account_List = [{'account_name': "user01", "acccount_password": "a123456"}, {'account_name': "user02", "acccount_password": "a654321"}]

    for account in account_List:
        # Instantiate business logic thread object
        LogicObject_Thread = SeleniumLogicMethods(account)
        # Start thread
        LogicObject_Thread.start()
        LogicObject_Thread.join()

        # Get results from the business thread module
        # Call the "Get_Result()" method in the thread object to collect results
        _res = LogicObject_Thread.Get_Result()
        print(_res)


Ouput:
Attack account:user01 password:a123456
{'result': True}
Attack account:user02 password:a654321
{'result': True}


As you can see, the dictionary type is returned.
Then, after the results are collected, we only need to define a list to save the results.

Thread_Get_Result.py:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 2022-08-25
# Breached.to Bullet Class: mejuri Project
# THE FAST ONLINE VERSION 1.0CB

# Import thread from threading standard library
from threading import Thread

# We pretend to create a "business class":
# Why? Because we plan to encapsulate the business logic into modules and then use threads to execute
class SeleniumLogicMethods(Thread):

    def __init__(self, account_info):
        super(SeleniumLogicMethods, self).__init__()
        self.AC_INFO = account_info

        # Define a result: default False
        self.result_TaskDict = {"result": False}

    def run(self):
        print("Attack account:{} password:{}".format(self.AC_INFO['account_name'], self.AC_INFO['acccount_password']))

        # Suppose a result:
        _tmp_Result = True
        if _tmp_Result:
            # If the result meets the expected value: Set the value of "self.result_TaskDict"
            self.result_TaskDict = {"result": True}

    def Get_Result(self):
        """
        Return result
        :return:
        """
        try:
            return self.result_TaskDict
        except Exception:
            return self.result_TaskDict


if __name__ == '__main__':
    # Save result list
    RESULT = []

    # Create a list. Suppose this is the account list
    account_List = [{'account_name': "user01", "acccount_password": "a123456"}, {'account_name': "user02", "acccount_password": "a654321"}]

    for account in account_List:
        # Instantiate business logic thread object
        LogicObject_Thread = SeleniumLogicMethods(account)
        # Start thread
        LogicObject_Thread.start()
        LogicObject_Thread.join()

        # Get results from the business thread module
        # Call the "Get_Result()" method in the thread object to collect results
        _res = LogicObject_Thread.Get_Result()

        RESULT.append(_res)
        print("Debug Info: Save the results to the results list - value: {}".format(_res))

    print("Debug Info: Ultimate result -> {}".format(RESULT))


Output:
Attack account:user01 password:a123456
Debug Info: Save the results to the results list - value: {'result': True}
Attack account:user02 password:a654321
Debug Info: Save the results to the results list - value: {'result': True}
Debug Info: Ultimate result -> [{'result': True}, {'result': True}]


Finally, combined with the knowledge learned in this lesson, can you collect the results of the previous courses by yourself?
Believe in yourself and try again! ^_^
Reply


 Users viewing this thread: Python + Selenium: Thread module encapsulationCollect results from threads.[SE12]: No users currently viewing.