为ini文件中的每个部分分配一个线程

0 投票
1 回答
1001 浏览
提问于 2025-04-18 11:25

我正在使用这个工具包:https://github.com/Fire30/Fifa14Client,它是用Python 2.7写的。

from Fifa14Client import LoginManager
from Fifa14Client import WebAppFunctioner
import ConfigParser
from extra import EAHash
import threading


def do_main():
    Config = ConfigParser.ConfigParser()
    Config.read("accounts_example.ini")
    for section in Config.sections():
        email = Config.get(section, 'Email')
        password = Config.get(section, 'Password')
        secret_answer = Config.get(section, 'Secret')
        security_hash = EAHash.EAHashingAlgorithm().EAHash(secret_answer)
        platform = Config.get(section, 'Platform')

        login = LoginManager.LoginManager(email,password,security_hash,platform)
        login.login()
        func = WebAppFunctioner.WebAppFunctioner(login)

我脚本的这一部分是用来访问一个ini文件,这个文件里存储着网站账户的登录信息,然后进行登录。这个ini文件里有不同的部分,每个部分都有自己的账户,格式大致是这样的:

[AccountOne]

邮箱:xxx@xxx.com

密码:qwerty123

密保问题答案:answer

平台:xbox

[AccountTwo]

邮箱:xxx@xxx.com

密码:qwerty123

密保问题答案:answer

平台:xbox

依此类推。我想做的是给每个账户分配一个线程,这样每个账户就可以在自己的线程中运行。

如果我说得不太清楚,抱歉,提前谢谢大家的帮助。

1 个回答

0

你可以简单地使用 threading.Thread 来实现这个功能:

from Fifa14Client import LoginManager
from Fifa14Client import WebAppFunctioner
import ConfigParser
from extra import EAHash
import threading


def login_thread(email, password, security_hash, platform):
    # This function runs in a separate thread.
    login = LoginManager.LoginManager(email,password,security_hash,platform)
    login.login()
    func = WebAppFunctioner.WebAppFunctioner(login)
    # Do more stuff here

def do_main():
    Config = ConfigParser.ConfigParser()
    Config.read("accounts_example.ini")
    threads = []
    for section in Config.sections():
        email = Config.get(section, 'Email')
        password = Config.get(section, 'Password')
        secret_answer = Config.get(section, 'Secret')
        security_hash = EAHash.EAHashingAlgorithm().EAHash(secret_answer)
        platform = Config.get(section, 'Platform')
        t = threading.Thread(target=login_thread, 
                             args=(email, password, security_hash, platform))
        t.start()
        threads.append(t)

    for t in threads: # Wait for all the threads to finish
        t.join()

需要注意的是,由于存在 全局解释器锁(GIL),在Python中,线程无法在多个CPU核心上同时运行,所以你无法实现真正的并行处理。如果想要实现并行处理,你应该使用 multiprocessing 库,它的使用方式和 threading 非常相似,但不受GIL的限制;它是通过子进程来实现并行,而不是线程。要将上面的代码改成使用这个库,只需要把 threading.Thread 改成 multiprocessing.Process 就可以了。

撰写回答