python字节码文件后缀_将任意命名的文件作为Python模块导入,而不生成字节码fi...

到目前为止,我最好的实现是(仅在Python2.6或更高版本中使用特性):import os

import sys

import imp

import contextlib

@contextlib.contextmanager

def preserve_value(namespace, name):

""" A context manager to preserve, then restore, the specified binding.

:param namespace: The namespace object (e.g. a class or dict)

containing the name binding.

:param name: The name of the binding to be preserved.

:yield: None.

When the context manager is entered, the current value bound to

`name` in `namespace` is saved. When the context manager is

exited, the binding is re-established to the saved value.

"""

saved_value = getattr(namespace, name)

yield

setattr(namespace, name, saved_value)

def make_module_from_file(module_name, module_filepath):

""" Make a new module object from the source code in specified file.

:param module_name: The name of the resulting module object.

:param module_filepath: The filesystem path to open for

reading the module's Python source.

:return: The module object.

The Python import mechanism is not used. No cached bytecode

file is created, and no entry is placed in `sys.modules`.

"""

py_source_open_mode = 'U'

py_source_description = (".py", py_source_open_mode, imp.PY_SOURCE)

with open(module_filepath, py_source_open_mode) as module_file:

with preserve_value(sys, 'dont_write_bytecode'):

sys.dont_write_bytecode = True

module = imp.load_module(

module_name, module_file, module_filepath,

py_source_description)

return module

def import_program_as_module(program_filepath):

""" Import module from program file `program_filepath`.

:param program_filepath: The full filesystem path to the program.

This name will be used for both the source file to read, and

the resulting module name.

:return: The module object.

A program file has an arbitrary name; it is not suitable to

create a corresponding bytecode file alongside. So the creation

of bytecode is suppressed during the import.

The module object will also be added to `sys.modules`.

"""

module_name = os.path.basename(program_filepath)

module = make_module_from_file(module_name, program_filename)

sys.modules[module_name] = module

return module

这有点过于宽泛:它在模块的整个导入过程中禁用字节码文件生成,这意味着在此过程中导入的其他模块也不会生成字节码文件。在

我仍然在寻找一种方法来禁用指定模块文件的字节码文件生成。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值