如何从多个 .py 文件中获取字节码?

How to get bytecode from several .py files?

我是编程新手,正在从事一个探索 Python 字节码的项目。我有几个扩展名为 .py 的 python 文件,想使用 dis.dis() 函数来保存相当于很多小程序的字节码。

例如下面的代码,当运行时,将return函数的字节码(def部分)。我的问题是我找不到将文件导入为 text/code 的解决方案,因为它们定义了所有函数,并且 运行 这段代码包含了数千个示例。

import dis

def something():
    n = int(raw_input())

    if n % 2 == 0:
        print (n, "is even")
    else:
        print (n, "is odd")

dis.dis(something)

有人有解决办法吗?我想要一个循环或类似的东西,它将 .py 文件作为文本拉入,将其粘贴到 def,然后 运行s 代码,保存结果。我可以弄清楚 运行 宁和保存部分,我只是找不到任何从 .py 文件中“粘贴”代码的东西,在 def.

更新

根据建议(非常感谢!),我尝试了以下代码。我使用了其他 Whosebug 问题和答案并尝试解决问题。代码 运行s 没有错误,甚至执行了最后一个打印语句,并生成了 pyc 文件,但是,我无法捕获 dis.dis(code_obj, file=out) 输出,它甚至不打印或保存。您对我哪里出错有什么建议吗?

import py_compile
from os import walk

# Define the path to compile from
mypath = 'C:/mydirectorycomeshere/SourceCodeChecker/'

# Assign the list of filenames in the mypath folder
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break
print('List read')

# Compile all files to pyc
py_compile.main(filenames)

# Define the path where these will be compiled
comppath = 'C:/mydirectorycomeshere/__pycache__/'

# Create new list with compiled files
f2 = []
for (dirpath, dirnames, filenames) in walk(comppath):
    f2.extend(comppath)
    break
print('Compiled list ready')

# Create bytecode from complied files and save them

import marshal, sys
import dis
import os
from io import StringIO

folderpath = r'C:/mydirectorycomeshere/__pycache__/'
filepaths = [os.path.join(folderpath, name) for name in os.listdir(folderpath)]
all_files = []

# Set header for marshal read of pyc files based on version

header_size = 8
if sys.version_info >= (3, 6):
    header_size = 12
if sys.version_info >= (3, 7):
    header_size = 16
print('Header set up ready')

# Iterate through compiled files and save or print output

import glob
for filename in glob.glob('*.pyc'):
   with open(os.path.join(os.cwd(), filename), 'r') as f:
       metadata = f3.read(header_size)
       code_obj = marshal.load(f3)
       with StringIO() as out:
           dis.dis(code_obj, file=out)
           print(out.getvalue())
           file.write(out)
       file = f.readlines()
       all_files.append(file)
print('Program ready')

在主管的帮助下,我设法找到了解决方案。这不考虑特殊情况,例如文件名中的 space,但确实通过将字节码保存在 .txt 文件中解决了问题:

from os import walk
import glob
import os
# Define the path to compile from
mypath = 'C:/yourfoldercomeshere/'

# Assign the list of filenames in the mypath folder
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break
print(filenames)
#Iterate through files, dis them and save them:

for filenames in glob.glob('*.py'):
      outfilename = filenames.replace('py', 'txt')
      print(outfilename)
      filenames=("python -m dis {0} > {1}".format(filenames,outfilename))
      os.system(filenames)
print(outfilename)