gpt4 book ai didi

python - 是否有python函数可以为python代码字符串生成字节码?

转载 作者:行者123 更新时间:2023-11-28 21:21:59 25 4
gpt4 key购买 nike

例如我可以做这样的事情吗

pythonCode = "print 'hello world'"
pyc = generate_bytecode(pythonCode)

pyc 在哪里包含 pythonCode 的字节码?

编辑:我的目标本质上是准确获取将写入 .pyc 文件的内容到变量中。魔数(Magic Number)、时间戳、代码的十六进制版本和所有

最佳答案

'exec' 作为 mode 传递给 compile()将从 Python 语句生成一个代码对象。访问代码对象的 co_code 属性将为您提供原始字节码。请注意,如果没有其他 co_* 属性,仅此一项将毫无用处。

>>> c = compile('print a', '<string>', 'exec')
>>> dir(c)
['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> c.co_code
'e\x00\x00GHd\x00\x00S'
>>> c.co_names
('a',)
>>> c.co_consts
(None,)
>>> dis.dis(c)
1 0 LOAD_NAME 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE

关于python - 是否有python函数可以为python代码字符串生成字节码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com