如何在python

时间:2017-09-13 17:21:39

标签: python python-2.7

我正在使用python,我应该从命令行读取文件以进行进一步处理。我的输入文件有一个二进制文件,应该读取以便进一步处理。这是我的输入文件sub.py:

   CODE = " \x55\x48\x8b\x05\xb8\x13\x00\x00"

我应该阅读的主文件如下:

import pyvex
import archinfo
import fileinput

import sys
filename = sys.argv[-1]


f = open(sys.argv[-1],"r")
CODE = f.read()
f.close()
print CODE

#CODE = b"\x55\x48\x8b\x05\xb8\x13\x00\x00"
# translate an AMD64 basic block (of nops) at 0x400400 into VEX
irsb = pyvex.IRSB(CODE, 0x1000, archinfo.ArchAMD64())

# pretty-print the basic block
irsb.pp()

# this is the IR Expression of the jump target of the unconditional exit at the end of the basic block
print irsb.next

# this is the type of the unconditional exit (i.e., a call, ret, syscall, etc)
print irsb.jumpkind

# you can also pretty-print it
irsb.next.pp()

# iterate through each statement and print all the statements
for stmt in irsb.statements:
        stmt.pp()

# pretty-print the IR expression representing the data, and the *type* of that IR expression written by every store statement
import pyvex
for stmt in irsb.statements:
  if isinstance(stmt, pyvex.IRStmt.Store):
    print "Data:",
    stmt.data.pp()
    print ""

    print "Type:",
    print stmt.data.result_type
    print ""

# pretty-print the condition and jump target of every conditional exit from the basic block
for stmt in irsb.statements:
        if isinstance(stmt, pyvex.IRStmt.Exit):
                print "Condition:",
                stmt.guard.pp() 
                print "" 

                print "Target:",
                stmt.dst.pp()
                print ""

# these are the types of every temp in the IRSB
print irsb.tyenv.types

# here is one way to get the type of temp 0
print irsb.tyenv.types[0]

问题在于,当我运行" python maincode.py sub.py'它将代码读作文件的内容,但其输出与我直接将CODE添加到语句irsb = pyvex.IRSB(CODE, 0x1000, archinfo.ArchAMD64())时的输出完全不同。有谁知道问题是什么,我该如何解决?我甚至使用从inputfile导入,但它不读取文本。

2 个答案:

答案 0 :(得分:1)

您是否考虑过__import__方式?

你可以做到

mod = __import__(sys.argv[-1])
print mod.CODE

并且只传递没有.py扩展名的文件名作为命令行参数:

python maincode.py sub

编辑:显然使用__import__discouraged。相反,尽管您可以使用importlib模块:

import sys,importlib
mod = importlib.import_module(sys.argv[-1])
print mod.CODE

..它应该与使用__import__

相同

如果需要将路径传递给模块,一种方法是在每个目录中添加一个名为

的空文件
__init__.py

这将允许python将目录解释为模块名称空间,然后您可以以模块形式传递路径:python maincode.py path.to.subfolder.sub

如果由于某种原因您不能或不想将目录添加为命名空间,并且不想在任何地方添加init.py文件,您也可以使用imp.find_module。你的maincode.py看起来像这样:

import sys, imp
mod  = imp.find_module("sub","/path/to/subfolder/")
print mod.code

您必须编写代码,将命令行输入分解为模块部分" sub"和文件夹路径" / path / to / subfolder /"虽然。那有意义吗?一旦准备就绪,您就会像预期的那样召唤它,python maincode.py /path/to/subfolder/sub/

答案 1 :(得分:0)

您正在以文本形式阅读代码,而在阅读文件时,您可能会将其视为二进制文件

您可能需要将二进制文件转换为反之亦然的文本

Binary to String/Text in Python

相关问题