0
#!/usr/bin/env python`
import sys`
import binascii`
import string
sample = "foo.apples"
data_file = open("file1.py","r")
dat_file = open("file2.txt", "w")
for line in data_file:
    if sample in line:
        dat_file.writelines(line)
 dat_file.close()`

当我这样做时,我能够找到字符串 foo.apples。问题foo.apples存在于 python 文件的各个行中。我想要那些在特定函数内的行。我需要这个 def 函数中的行。

Example:

def start():
    foo.apples(a,b)
    foo.apples(c,d) ... so on.   
4

3 回答 3

0

一,稍微偏离常规的方法是使用模块的getsource方法。inspect考虑以下(理论)test1.py文件:

class foo(object):
    apples = 'granny_smith'
    @classmethod
    def new_apples(cls):
        cls.apples = 'macintosh'

def start():
    """This is a pretty meaningless python function.
    Attempts to run it will definitely result in an exception being thrown"""
    print foo.apples
    foo.apples = 3
    [x for x in range(10)]
    import bar as foo

现在您想了解start代码:

import inspect
import test1  #assume it is somewhere that can be imported

print inspect.getsource(test1.start)

好的,现在我们只有该函数的来源。我们现在可以解析:

for line in inspect.getsource(test1.start).splitlines():
    if 'foo.apples' in line:
        print line

这里有一些优点——python 在导入文件时完成了解析功能块的所有工作。缺点是文件实际上需要导入。根据您的文件来自哪里,这可能会在您的程序中引入一个巨大的安全漏洞——您将运行(可能)“不受信任”的代码。

于 2012-12-18T21:55:18.140 回答
0

这是一种非常非 Pythonic 的方式,未经测试,但它应该可以工作。

sample = "foo.apples"
infile = open("file1.py", "r")
outfile = open("file2.txt", "w")
in_function = False

for line in infile.readlines():
    if in_function:
        if line[0] in(" ", "\t"):
            if sample in line:
                outfile.write(line)
        else:
            in_function = False
    elif line.strip() == "def start():":
        in_function = True
infile.close()
outfile.close()

我建议做一个这样的函数,它需要sample输入文件和我们应该搜索的函数作为它的参数。然后它将返回包含文本的所有行的列表或元组。

def findFromFile(file, word, function):
    in_function = False
    matches = []
    infile = open(file, "r")

    for line in infile.readlines():
        if in_function:
            if line[0] in(" ", "\t"):
                if word in line:
                    matches.append(line)
            else:
                in_function = False
        elif line.strip() == "def %s():"%function:
            in_function = True

    infile.close()
    return matches
于 2012-12-18T22:01:02.770 回答
0

以下程序找到defs 并将示例字符串附加到输出文件,如果缩进仍在def.

import re

sample = 'foo.apples'
data_file = open("file1.py", "r")
out_file = open("file2.txt", "w")
within_def = False
def_indent = 0

for line in data_file:
    def_match = re.match(r'(\s*)def\s+start\s*\(', line)  # EDIT: fixed regex
    if def_match and not within_def:
        within_def = True
        def_indent = len(def_match.group(1))
    elif within_def and re.match(r'\s{%s}\S' % def_indent, line):
        within_def = False

    if within_def and sample in line:
        out_file.writelines(line)

out_file.close()
data_file.close()

测试了一个例子file1.py

于 2012-12-18T22:14:21.037 回答