【发布时间】:2013-12-02 00:04:52
【问题描述】:
使用 Linux 和 Python 2.7.6,我有一个脚本可以一次上传大量文件。我在队列和线程模块中使用多线程。
我为 SIGINT 实现了一个处理程序,以在用户按 ctrl-C 时停止脚本。我更喜欢使用守护线程,所以我不必清除队列,这将需要大量重写代码以使 SIGINT 处理程序可以访问 Queue 对象,因为处理程序不接受参数。
为了确保守护线程在 sys.exit() 之前完成并清理,我使用 threading.Event() 和 threading.clear() 让线程等待。此代码似乎作为 print threading.enumerate() 仅在我进行调试时脚本终止之前显示主线程。只是为了确保,我想知道是否有任何关于这个清理实现的见解,即使它似乎对我有用:
def signal_handler(signal, frame):
global kill_received
kill_received = True
msg = (
"\n\nYou pressed Ctrl+C!"
"\nYour logs and their locations are:"
"\n{}\n{}\n{}\n\n".format(debug, error, info))
logger.info(msg)
threads = threading.Event()
threads.clear()
while True:
time.sleep(3)
threads_remaining = len(threading.enumerate())
print threads_remaining
if threads_remaining == 1:
sys.exit()
def do_the_uploads(file_list, file_quantity,
retry_list, authenticate):
"""The uploading engine"""
value = raw_input(
"\nPlease enter how many concurent "
"uploads you want at one time(example: 200)> ")
value = int(value)
logger.info('{} concurent uploads will be used.'.format(value))
confirm = raw_input(
"\nProceed to upload files? Enter [Y/y] for yes: ").upper()
if confirm == "Y":
kill_received = False
sys.stdout.write("\x1b[2J\x1b[H")
q = CustomQueue()
def worker():
global kill_received
while not kill_received:
item = q.get()
upload_file(item, file_quantity, retry_list, authenticate, q)
q.task_done()
for i in range(value):
t = Thread(target=worker)
t.setDaemon(True)
t.start()
for item in file_list:
q.put(item)
q.join()
print "Finished. Cleaning up processes...",
#Allowing the threads to cleanup
time.sleep(4)
def upload_file(file_obj, file_quantity, retry_list, authenticate, q):
"""Uploads a file. One file per it's own thread. No batch style. This way if one upload
fails no others are effected."""
absolute_path_filename, filename, dir_name, token, url = file_obj
url = url + dir_name + '/' + filename
try:
with open(absolute_path_filename) as f:
r = requests.put(url, data=f, headers=header_collection, timeout=20)
except requests.exceptions.ConnectionError as e:
pass
if src_md5 == r.headers['etag']:
file_quantity.deduct()
【问题讨论】:
标签: python linux multithreading