the .pyc file was compiled Python version

本文介绍了一种通过解析.pyc文件中的魔数来确定生成该文件的Python版本的方法。此外,还提供了一个Python脚本,可以检测从Python 1.5到Python 3.5a0版本的.pyc文件。

You can get the magic number of your Python as follows:

$ python -V
Python 2.6.2
# python
>>> import imp
>>> imp.get_magic().encode('hex')
'd1f20d0a'

To get the magic number for a pyc file you can do the following:

>>> f = open('test25.pyc')
>>> magic = f.read(4)
>>> magic.encode('hex')
'b3f20d0a'
>>> f = open('test26.pyc')
>>> magic = f.read(4)
>>> magic.encode('hex')
'd1f20d0a'

By comparing the magic numbers you'll know the python version that generated the pyc file.


The first two bytes of the .pyc file are the magic number that tells the version of the bytecodes. The word is stored in little-endian format, and the known values are:

# Python/import.c - merged by aix from Python 2.7.2 and Python 3.2.2
# EDIT: added little endian hex values for comparison first two bytes of Igor Popov's method -jimbob

       Python 1.5:   20121  0x994e
       Python 1.5.1: 20121  0x994e
       Python 1.5.2: 20121  0x994e
       Python 1.6:   50428  0x4cc4
       Python 2.0:   50823  0x87c6
       Python 2.0.1: 50823  0x87c6
       Python 2.1:   60202  0x2aeb
       Python 2.1.1: 60202  0x2aeb
       Python 2.1.2: 60202  0x2aeb
       Python 2.2:   60717  0x2ded
       Python 2.3a0: 62011  0x3bf2
       Python 2.3a0: 62021  0x45f2
       Python 2.3a0: 62011  0x3bf2 (!)
       Python 2.4a0: 62041  0x59f2
       Python 2.4a3: 62051  0x63f2
       Python 2.4b1: 62061  0x6df2
       Python 2.5a0: 62071  0x77f2
       Python 2.5a0: 62081  0x81f2 (ast-branch)
       Python 2.5a0: 62091  0x8bf2 (with)
       Python 2.5a0: 62092  0x8cf2 (changed WITH_CLEANUP opcode)
       Python 2.5b3: 62101  0x95f2 (fix wrong code: for x, in ...)
       Python 2.5b3: 62111  0x9ff2 (fix wrong code: x += yield)
       Python 2.5c1: 62121  0xa9f2 (fix wrong lnotab with for loops and
                            storing constants that should have been removed)
       Python 2.5c2: 62131  0xb3f2 (fix wrong code: for x, in ... in listcomp/genexp)
       Python 2.6a0: 62151  0xc7f2 (peephole optimizations and STORE_MAP opcode)
       Python 2.6a1: 62161  0xd1f2 (WITH_CLEANUP optimization)
       Python 2.7a0: 62171  0xdbf2 (optimize list comprehensions/change LIST_APPEND)
       Python 2.7a0: 62181  0xe5f2 (optimize conditional branches:
                introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
       Python 2.7a0  62191  0xeff2 (introduce SETUP_WITH)
       Python 2.7a0  62201  0xf9f2 (introduce BUILD_SET)
       Python 2.7a0  62211  0x03f3 (introduce MAP_ADD and SET_ADD)

       Python 3000:   3000  0xb80b
                      3010  0xc20b (removed UNARY_CONVERT)
                      3020  0xcc0b (added BUILD_SET)
                      3030  0xd60b (added keyword-only parameters)
                      3040  0xe00b (added signature annotations)
                      3050  0xea0b (print becomes a function)
                      3060  0xf40b (PEP 3115 metaclass syntax)
                      3061  0xf50b (string literals become unicode)
                      3071  0xff0b (PEP 3109 raise changes)
                      3081  0x090c (PEP 3137 make __file__ and __name__ unicode)
                      3091  0x130c (kill str8 interning)
                      3101  0x1d0c (merge from 2.6a0, see 62151)
                      3103  0x1f0c (__file__ points to source file)
       Python 3.0a4:  3111  0x270c (WITH_CLEANUP optimization).
       Python 3.0a5:  3131  0x3b0c (lexical exception stacking, including POP_EXCEPT)
       Python 3.1a0:  3141  0x450c (optimize list, set and dict comprehensions:
               change LIST_APPEND and SET_ADD, add MAP_ADD)
       Python 3.1a0:  3151  0x4f0c (optimize conditional branches:
           introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
       Python 3.2a0:  3160  0x580c (add SETUP_WITH)
                     tag: cpython-32
       Python 3.2a1:  3170  0x620c (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
                     tag: cpython-32
       Python 3.2a2   3180  0x6c0c (add DELETE_DEREF)


Take a look at my script in Python that detects and returns the version of Python by which the file (*.pyc or *.pyo) was compiled.

It detects versions of Python from Python 1.5 up to Python 3.5a0.


原文   http://stackoverflow.com/questions/7807541/is-there-a-way-to-know-by-which-python-version-the-pyc-file-was-compiled

Traceback (most recent call last): File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\_core\__init__.py", line 23, in <module> from . import multiarray File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\_core\multiarray.py", line 10, in <module> from . import overrides File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\_core\overrides.py", line 7, in <module> from numpy._core._multiarray_umath import ( ImportError: PyCapsule_Import could not import module "datetime" During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\__init__.py", line 114, in <module> from numpy.__config__ import show_config File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\__config__.py", line 4, in <module> from numpy._core._multiarray_umath import ( File "C:\Users\21904\PycharmProjects\PythonProject\.venv\lib\site-packages\numpy\_core\__init__.py", line 49, in <module> raise ImportError(msg) ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.10 from "C:\Users\21904\PycharmProjects\PythonProject\.venv\Scripts\python.exe" * The NumPy version is: "2.2.6" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: PyCapsule_Import could not import module "datetime"
最新发布
11-30
cyt@TT:~/ultralytics-main$ python3 mytrain.py Ultralytics 8.3.205 🚀 Python-3.10.12 torch-2.8.0+cu128 CUDA:0 (NVIDIA GeForce RTX 4060 Laptop GPU, 7915MiB) engine/trainer: agnostic_nms=False, amp=True, augment=False, auto_augment=randaugment, batch=-1, bgr=0.0, box=7.5, cache=ram, cfg=None, classes=None, close_mosaic=10, cls=0.5, compile=False, conf=None, copy_paste=0.0, copy_paste_mode=flip, cos_lr=False, cutmix=0.0, data=/home/cyt/ultralytics-main/ultralytics/cfg/datasets/elderly.yaml, degrees=0.0, deterministic=True, device=None, dfl=1.5, dnn=False, dropout=0.0, dynamic=False, embed=None, epochs=100, erasing=0.4, exist_ok=False, fliplr=0.5, flipud=0.0, format=torchscript, fraction=1.0, freeze=None, half=False, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, imgsz=640, int8=False, iou=0.7, keras=False, kobj=1.0, line_width=None, lr0=0.01, lrf=0.01, mask_ratio=4, max_det=300, mixup=0.0, mode=train, model=/home/cyt/ultralytics-main/yolo11n.pt, momentum=0.937, mosaic=1.0, multi_scale=False, name=myresult2, nbs=64, nms=False, opset=None, optimize=False, optimizer=auto, overlap_mask=True, patience=100, perspective=0.0, plots=True, pose=12.0, pretrained=True, profile=False, project=results, rect=False, resume=False, retina_masks=False, save=True, save_conf=False, save_crop=False, save_dir=/home/cyt/ultralytics-main/results/myresult2, save_frames=False, save_json=False, save_period=-1, save_txt=False, scale=0.5, seed=0, shear=0.0, show=False, show_boxes=True, show_conf=True, show_labels=True, simplify=True, single_cls=False, source=None, split=val, stream_buffer=False, task=detect, time=None, tracker=botsort.yaml, translate=0.1, val=True, verbose=True, vid_stride=1, visualize=False, warmup_bias_lr=0.1, warmup_epochs=3.0, warmup_momentum=0.8, weight_decay=0.0005, workers=1, workspace=None A module that was compiled using NumPy 1.x cannot be run in NumPy 2.2.6 as it may crash. To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. We expect that some modules will need time to support NumPy 2. Traceback (most recent call last): File "/home/cyt/ultralytics-main/mytrain.py", line 5, in <module> model.train( File "/home/cyt/ultralytics-main/ultralytics/engine/model.py", line 795, in train self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks) File "/home/cyt/ultralytics-main/ultralytics/models/yolo/detect/train.py", line 65, in __init__ super().__init__(cfg, overrides, _callbacks) File "/home/cyt/ultralytics-main/ultralytics/engine/trainer.py", line 158, in __init__ self.data = self.get_dataset() File "/home/cyt/ultralytics-main/ultralytics/engine/trainer.py", line 634, in get_dataset data = check_det_dataset(self.args.data) File "/home/cyt/ultralytics-main/ultralytics/data/utils.py", line 480, in check_det_dataset check_font("Arial.ttf" if is_ascii(data["names"]) else "Arial.Unicode.ttf") # download fonts File "/home/cyt/ultralytics-main/ultralytics/utils/__init__.py", line 500, in decorated return f(*args, **kwargs) File "/home/cyt/ultralytics-main/ultralytics/utils/checks.py", line 325, in check_font from matplotlib import font_manager # scope for faster 'import ultralytics' File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 109, in <module> from . import _api, _version, cbook, docstring, rcsetup File "/usr/lib/python3/dist-packages/matplotlib/rcsetup.py", line 27, in <module> from matplotlib.colors import Colormap, is_color_like File "/usr/lib/python3/dist-packages/matplotlib/colors.py", line 56, in <module> from matplotlib import _api, cbook, scale File "/usr/lib/python3/dist-packages/matplotlib/scale.py", line 23, in <module> from matplotlib.ticker import ( File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 136, in <module> from matplotlib import transforms as mtransforms File "/usr/lib/python3/dist-packages/matplotlib/transforms.py", line 46, in <module> from matplotlib._path import ( AttributeError: _ARRAY_API not found Traceback (most recent call last): File "/home/cyt/ultralytics-main/ultralytics/engine/trainer.py", line 634, in get_dataset data = check_det_dataset(self.args.data) File "/home/cyt/ultralytics-main/ultralytics/data/utils.py", line 480, in check_det_dataset check_font("Arial.ttf" if is_ascii(data["names"]) else "Arial.Unicode.ttf") # download fonts File "/home/cyt/ultralytics-main/ultralytics/utils/__init__.py", line 500, in decorated return f(*args, **kwargs) File "/home/cyt/ultralytics-main/ultralytics/utils/checks.py", line 325, in check_font from matplotlib import font_manager # scope for faster 'import ultralytics' File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 109, in <module> from . import _api, _version, cbook, docstring, rcsetup File "/usr/lib/python3/dist-packages/matplotlib/rcsetup.py", line 27, in <module> from matplotlib.colors import Colormap, is_color_like File "/usr/lib/python3/dist-packages/matplotlib/colors.py", line 56, in <module> from matplotlib import _api, cbook, scale File "/usr/lib/python3/dist-packages/matplotlib/scale.py", line 23, in <module> from matplotlib.ticker import ( File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 136, in <module> from matplotlib import transforms as mtransforms File "/usr/lib/python3/dist-packages/matplotlib/transforms.py", line 46, in <module> from matplotlib._path import ( ImportError: numpy.core.multiarray failed to import The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/cyt/ultralytics-main/mytrain.py", line 5, in <module> model.train( File "/home/cyt/ultralytics-main/ultralytics/engine/model.py", line 795, in train self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks) File "/home/cyt/ultralytics-main/ultralytics/models/yolo/detect/train.py", line 65, in __init__ super().__init__(cfg, overrides, _callbacks) File "/home/cyt/ultralytics-main/ultralytics/engine/trainer.py", line 158, in __init__ self.data = self.get_dataset() File "/home/cyt/ultralytics-main/ultralytics/engine/trainer.py", line 638, in get_dataset raise RuntimeError(emojis(f"Dataset '{clean_url(self.args.data)}' error ❌ {e}")) from e RuntimeError: Dataset '/home/cyt/ultralytics-main/ultralytics/cfg/datasets/elderly.yaml' error ❌ numpy.core.multiarray failed to import
10-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值