我正在尝试调试多线程脚本.一旦异常被提出,我想:
我准备了非常复杂的例子来展示我是如何尝试解决它的:
#!/usr/bin/env python
import threading
import inspect
import traceback
import sys
import os
import time
def POST_PORTEM_DEBUGGER(type, value, tb):
traceback.print_exception(type, value, tb)
print
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
import rpdb
rpdb.pdb.pm()
else:
import pdb
pdb.pm()
sys.excepthook = POST_PORTEM_DEBUGGER
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.exception = None
self.info = None
self.the_calling_script_name = os.path.abspath(inspect.currentframe().f_back.f_code.co_filename)
def main(self):
"Virtual method to be implemented by inherited worker"
return self
def run(self):
try:
self.main()
except Exception as exception:
self.exception = …Run Code Online (Sandbox Code Playgroud) 我遇到了从以下脚本收集日志的问题.一旦我设置SLEEP_TIME为太"小"的值,LoggingThread线程就会以某种方式阻止日志记录模块.该脚本冻结了action函数中的日志记录请求.如果SLEEP_TIME大约为0.1,则脚本会按预期收集所有日志消息.
我试着按照这个答案,但它没有解决我的问题.
import multiprocessing
import threading
import logging
import time
SLEEP_TIME = 0.000001
logger = logging.getLogger()
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(): %(message)s'))
ch.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
class LoggingThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
logger.debug('LoggingThread: {}'.format(self))
time.sleep(SLEEP_TIME)
def action(i):
logger.debug('action: {}'.format(i))
def do_parallel_job():
processes = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=processes)
for i in range(20):
pool.apply_async(action, args=(i,))
pool.close()
pool.join()
if __name__ == '__main__':
logger.debug('START')
#
# multithread part
#
for _ in range(10): …Run Code Online (Sandbox Code Playgroud) 以下脚本:
import os
def call_close(fd):
try:
print fd
os.close(fd)
except Exception as e:
print 'Exception:', e
for fd in range(10):
call_close(fd)
Run Code Online (Sandbox Code Playgroud)
版画
0
1
Run Code Online (Sandbox Code Playgroud)
而已.没有例外.有什么猜测发生了什么?
我需要将标题(单行)添加到大量(> 10k)的文本文件中.假设变量$ HEADER确实包含适当的头.命令
find -type f -name 'tdgen_2012_??_??_????.csv' | xargs sed -i "1s/^/$HEADER\n/"
Run Code Online (Sandbox Code Playgroud)
确实运作良好.我面临的问题是一些数据文件(tdgen_2012_ ?? ?? ????.csv)是空的.sed(1)不能解决文件的非存在行.我决定以不同的方式管理空文件:
echo $HEADER | tee $(find -type f -name 'tdgen_2012_??_??_????.csv' -empty) > /dev/null
Run Code Online (Sandbox Code Playgroud)
由于空文件的数量,上面的命令不起作用.tee(1)无法写入无限数量的文件.还可以超过命令行参数的数量.
由于性能低,我不想使用for-cycle(tee(1)可以一次写入多个文件).
我的问题: