使用Python读取多行Python代码

2024-03-29 08:03:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python文件,我正在使用另一个Python文件读取它。我有电话。你知道吗

CP.TEST.AppendList(Name='MANHOLE', Values=[ 1, 2, ],
        var='MV')
CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],
        var='LV')

我正在用

if 'LV' in line:
     print line

因此,我得到的输出是:

            var='LV')

但是,我想得到包含该字符串的完整行。我的文件中有许多这样的多行python代码。你知道吗

如何使用python在代码中检索这样的python多行?你知道吗

例如,在这段代码中,我需要输出为

CP.TEST.AppendList(Name='MANHOLE', Values=[ 1, 2, ],
        var='LV')

使用值“LV”


Tags: 文件代码nametestifvarlinecp
2条回答

要理解多行代码实际上是一行python代码,您需要一些理解python的东西。你知道吗

在python中,您可以从代码获取编译器。“compile”命令可以获取文本并返回代码对象,或者在代码语法不正确时抛出错误:

try:
  compile(candidate_code, 'fake filename', 'exec')
  # got here? candidate_code compiles
except:
  # got here? candidate_code doesn't compile

编译完全可以容忍缺少符号定义的情况。但是,它不喜欢看到额外的缩进。你知道吗

使用它,我们可以逐步遍历代码行,查找多行语句(成功编译的行组)并测试任何为目标字符串编译的语句。我们必须将所有行编译到当前行(否则如果您的语句缩进,它就不会编译),并跟踪实际测试的行数(使用numcandidatelines)。另一种方法可能是简单地检测并去除多余的压痕。你知道吗

def findPythonLines(aContainsStr, lines):
  numcandidatelines = 0
  for index, line in enumerate(lines):
    numcandidatelines += 1

    try:
      candidate_code = "\n".join(lines[:index+1])
      candidate_statement = "\n".join(lines[index+1-numcandidatelines: index+1])

      compile(candidate_code, 'fake filename', 'exec') # or 'exec'

      # if we get here, this is a new possible result
      if aContainsStr in candidate_statement:
        return candidate_statement
      else:
        # no dice. Well, we need to look for the next candidate
        numcandidatelines = 0
    except:
      pass

  return None

# say input.txt contains the following:
# x = 10
#
# while (x 
#       > 0):
#   g()
#   
#   y = f(Name='MANHOLE', Values=[ 1, 2, ],
#       var='LV')
#  
#   x -= 1

with open ("input.txt", "r") as myfile:
    full_code_lines=myfile.readlines()

print "result: %s" % findPythonLines("'LV'", full_code_lines)

# prints out the following:
#
# result:   
#    y = f(Name='MANHOLE', Values=[ 1, 2, ],
#          var='LV')

您需要将编码为多行的单行连接起来,但它们都以','结尾(如果您下面的pep8是代码) 例如:

CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],
        var='LV')

将其临时转换为:

CP.TEST.AppendList(Name='CANHOLE', Values=[ 3, 4, ],var='LV')

现在开始搜索

with open('colorlabel.py','r') as file:
    temp=''
    for i in file:
        if i.strip().endswith(','):
            temp+=i
        else:
            temp+=i
            if 'lv' in temp:
                print '  >>',temp
            temp=""

相关问题 更多 >