What is an alternative to execfile in Python 3?

前端 未结 12 1801
滥情空心
滥情空心 2020-11-22 02:33

It seems they canceled in Python 3 all the easy way to quickly load a script by removing execfile()

Is there an obvious alternative I\'m missing?

12条回答
  •  一生所求
    2020-11-22 02:59

    Note that the above pattern will fail if you're using PEP-263 encoding declarations that aren't ascii or utf-8. You need to find the encoding of the data, and encode it correctly before handing it to exec().

    class python3Execfile(object):
        def _get_file_encoding(self, filename):
            with open(filename, 'rb') as fp:
                try:
                    return tokenize.detect_encoding(fp.readline)[0]
                except SyntaxError:
                    return "utf-8"
    
        def my_execfile(filename):
            globals['__file__'] = filename
            with open(filename, 'r', encoding=self._get_file_encoding(filename)) as fp:
                contents = fp.read()
            if not contents.endswith("\n"):
                # http://bugs.python.org/issue10204
                contents += "\n"
            exec(contents, globals, globals)
    

提交回复
热议问题