配置文件GUI应用程序引导程序

时间:2011-11-11 09:51:46

标签: python profiling

我有一些应用程序的启动时间非常慢。

从理论上讲,我只想在gui开火后立即退出。到现在为止,我已经手工完成了它,并且它有效,但我想知道是否有更好的方法......

当然解决方案是添加一个“sys.exit”,我想让它退出,但我应该修改代码。

有没有办法在不修改文件的情况下检测文件以退出?

1 个答案:

答案 0 :(得分:0)

好吧那么,实际设置一个“退出点”正好在我想要的地方而不触及代码并不是那么微不足道。

我认为可以使用 sys.settrace 进行操作,如下所示 http://www.doughellmann.com/PyMOTW/sys/tracing.html

所以我的解决方案是实际修改代码,只需在某个时刻添加退出行。

我想使用difflib,但它没有修补功能,所以我在下面创建了一个小脚本,简而言之: - 读取文件 - 插入/删除一行(插入时与前一行相同的缩进) - 重写它

#TODO: must make sure about the indentation
import argparse
import re
import sys

PATCH_LINE = "import sys; sys.exit(0)  # PATCHED"


def parse_arguments():
    # take the file and the line to patch, or maybe we can take a
    # diff file generated via uniform_diff
    parser = argparse.ArgumentParser(description='enable and disable the automatic exit')
    parser.add_argument('file', help='file to patch')

    parser.add_argument('line', help='line where to quit')

    parser.add_argument('-m', '--msg',
                        default=PATCH_LINE)

    parser.add_argument('-d', '--disable',
                        action='store_true')

    return parser.parse_args()


if __name__ == '__main__':
    ns = parse_arguments()
    text = open(ns.file).readlines()
    line_no = int(ns.line)

    if ns.disable:
        # the line should not be necessary in that case?
        text.remove(text[line_no])
    else:
        # count spaces
        prev = text[line_no - 1]
        m = re.match('\s*', prev)
        to_insert = m.group() + ns.msg
        print("inserting line %s" % to_insert)
        text.insert(line_no, to_insert)

    open(ns.file, 'w').writelines(text)
相关问题