忍受我 - 这是我的第一个多线程/处理python项目。让多个进程/线程始终运行,访问sqlite3数据库,直到满足条件
我正在其上应该运行some.exe其中每个需要的ID作为参数的Ñ实例一个Python脚本。这些ID是从本地sqlite数据库中提取的,并且如果成功处理则删除。任何ID都不能由一次处理多个some.exe(因此WORK 布尔型)。
我知道,下面的pool.map
需要ITER某种但是这是我的,包括任何形式的多功能使用线程/处理的第一个项目,我不知道该怎么处理它。
该脚本应该运行,直到没有ID剩下 - 持续运行n实例some.exe。 some.exe将可能需要1-6分钟为每个ID。
如果相关,这将运行在Windows机器上。
的代码部分只是伪代码和所有非必要的部分已经被省略:
#!/usr/bin/python
import time, sqlite3
from datetime import datetime
from multiprocessing.pool import ThreadPool as Pool
def run_worker(lite_cur):
lite_cur.execute("SELECET ID FROM IDS WHERE WORK != 1")
found_id = lite_cur.fetchone()
lite_cur.execute("UPDATE IDS SET WORK = 1 WHERE ID = \'"+found_id+"\'")
#starting a subprocess in a pool is probably not what one should do.. help?
process = subprocess.Popen(["some.exe", found_id])
process.wait()
#how would one check if some.exe chrashed or completed successfully?
if process = "some.exe completed without errors!":
lite_cur.execute("DELETE FROM IDS WHERE ID = \'"+found_id+"\'")
else:
#do this if some.exe crashed or reported errors.
lite_cur.execute("UPDATE IDS SET WORK = 0 WHERE ID = \'"+found_id+"\'")
def run_checker(lite_cur, ids_left):
time.sleep(600)
lite_cur.execute("SELECT * FROM IDS")
#may exceed 1 million, is there a better/faster way?
if len(lite_cur.fetchall()) == 0:
ids_left = False
def main():
#lite_db_name will be implemented as an argument.
lite_db_name = "some.db"
lite_con = sqlite3.connect(lite_db_name)
lite_cur = lite_con.cursor()
#IDs should be self-explanatory and WORK is used as a boolean to define if a worker is already working on this ID
lite_cur.execute("CREATE TABLE IF NOT EXISTS IDS(ID TEXT, WORK INTEGER DEFAULT 0)")
#max_worker will be implemented as an argument
max_worker = 4
worker_pool = Pool(max_worker)
#a pool with the limit of 1 is probably dumb as duck..
checker_pool = Pool(1)
lite_cur.execute("SELECT * FROM IDS")
if len(lite_cur.fetchall()) > 0:
ids_left = True
else:
ids_left = False
while ids_left:
worker_pool.map(run_worker(lite_cur))
checker_pool.map(run_checker(lite_cur, ids_left))
end_time = datetime.now()
print ("Congratulation - All IDs processed.")
print ("It took: {}".format(end_time - start_time))
if __name__ == "__main__":
main()
我会非常感谢您的任何建议和意见。
编辑:抱歉没有发布明确的问题。这个问题的意图是为任何进一步的发展获得一些领先的建议。
您能否澄清一下具体的问题是什么? – 2014-10-01 08:57:12
对具体问题没有明确的问题。我想你会期待某种“如何”。如果您的介绍几乎不匹配来源,那就更困难了。甚至没有一个句子以问号结尾。我想这是因为你自己不确定你是否有问题。没有绝对的“正确”方式。以一种您仍然可以在一年内了解您的源/解决方案的方式解决您的问题。 – 2014-10-01 08:57:33
@DonQuestion你是对的。我没有要求具体的答案,也没有要求。我要求你引导我去*正确的方向,或者给我一些提示,告诉我如何完成其余的伪代码部分。我担心*问题不会很受欢迎,但无论如何我都会问,因为我经常从评论或回答中获得帮助,这给了我一个方向提示。 – 2014-10-01 09:13:33