当我使用“ pip install”安装软件包时,随机临时目录的路径将记录在pyc文件中,如何消除这种随机差异?(如下 2b2_9obo < / strong>)
# uncompyle6 tools.cpython-37.pyc | head -n6
# uncompyle6 version 3.6.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.3 (default, Mar 6 2020, 14:23:55)
# [GCC 4.8.5]
# Embedded file name: /tmp/pip-unpacked-wheel-2b2_9obo/diffoscope/tools.py
# Size of source mod 2**32: 4106 bytes
答案 0 :(得分:0)
可能有一种在字节码上使用普通的旧POSIX sed
的方法,并且只要文件名没有出现在代码对象的co_filename
字段中,文件名就不会出现。
但是,如果您需要更防弹的解决方案,可以通过以下方法修改字节码并将其写回。
#!/usr/bin python
"""
Renames the co_filename object
"""
import glob, re, types
import os.path as osp
from xasm.misc import write_pycfile
from xasm.assemble import Assembler
from xdis.code import iscode
from xdis.load import load_module
from collections import deque
def change_co_filename(code, new_path):
return types.CodeType(
code.co_argcount,
code.co_kwonlyargcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co_names,
code.co_varnames,
new_path,
code.co_name,
code.co_firstlineno,
code.co_lnotab,
code.co_freevars,
code.co_cellvars)
def disco_loop(queue, new_path):
new_code = change_co_filename(queue[0], new_path)
while len(queue) > 0:
co = queue.popleft()
for c in co.co_consts:
if iscode(c):
change_co_filename(c, new_path)
queue.append(c)
pass
pass
return new_code
suffix = "cpython-3.7.pyc"
paths = glob.glob(f"*.{suffix}")
# Modify to figure out what prefix to look for
orig_dirname = "/tmp/pip-unpacked-wheel-2b2_9obo/"
new_dirname = "/tmp/"
for path in paths:
assembler = Assembler("3.7")
version, assembler.timestamp, magic_int, code, is_pypy, assembler.size = load_module(path)
new_path = re.sub(orig_dirname, new_dirname, code.co_filename)
queue = deque([code])
new_code = disco_loop(queue, new_path)
assembler.code_list = [new_code]
write_pycfile(path, assembler)
这取决于我的xdis
和xasm
程序在字节码上的工作。 (由于代码对象在该版本中更改,我刚才不得不将后者修改为3.7)
如果对这种东西感兴趣,我可以将上面的内容修改为一个独立的例程,并使用xasm分发它。
如果您想查看编写Python字节码文件的过程,请参见the answer here
答案 1 :(得分:0)
您可以先下载该软件包,然后手动对其进行编译:
pip install tools
python -m compileall -d nameofchoice
但是,这不会使您的构建具有可复制性。
.pyc
标头仍将包含一个时间戳。
从python 3.7开始,您可以使用非默认的无效模式进行编译。
pip install tools
python -m compileall --invalidation-mode unchecked-hash -d nameofchoice
这可能会使您的.pyc
文件具有可复制性。