[英]Search for a string with in a module in a python file using Python
#!/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.
一种稍微偏离getsource
方法是使用inspect
模块的getsource
方法。 考虑以下(理论上)的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在导入文件时完成了解析功能块的所有工作。 缺点是实际上需要导入文件。 根据文件的来源,这可能会在程序中引入巨大的安全漏洞-您将(潜在地)运行“不受信任”的代码。
这是一种非常非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
以下程序查找def
,如果缩进仍在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
上的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.