【问题标题】:Assign a thread to each section in an ini file为 ini 文件中的每个部分分配一个线程
【发布时间】:2014-06-28 14:02:48
【问题描述】:

我在 python 2.7 中使用这个工具包:https://github.com/Fire30/Fifa14Client

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

秘密:答案

平台:xbox

[AccountTwo]

邮箱:xxx@xxx.com

密码:qwerty123

秘密:答案

平台:xbox

等等。我想要做的是为每个帐户分配一个线程,以便每个帐户都有一个单独的线程

对不起,如果我有点不清楚,提前谢谢

【问题讨论】:

  • 好吧,看起来你知道你需要threading 模块。您是否尝试过在代码中实际使用它?如果可以,您可以分享您的尝试吗?
  • 我已将帐户分配给一个线程,但问题是它们都被分配给一个线程

标签: python multithreading python-requests python-multithreading sections


【解决方案1】:

您可以简单地使用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()

请记住,由于Global Interpreter Lock (GIL),Python 中的线程无法跨 CPU 内核并发运行,因此您无法实现真正​​的并行性。为此,您应该使用multiprocessing 库,它的API 与threading 几乎相同,但不受GIL 限制;它使用子进程进行并行处理,而不是线程。上述代码中进行切换所需的唯一更改是使用multiprocessing.Process 而不是threading.Thread

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2020-02-11
    • 2021-12-31
    • 2018-03-13
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2014-06-05
    相关资源
    最近更新 更多