I want to extract the code written under a specified function. I am trying to do it like this:
With an example file TestFile.py
containing the following function sub()
:
def sub(self,num1,num2):
# Subtract two numbers
answer = num1 - num2
# Print the answer
print('Difference = ',answer)
If I run get_func_data.py
:
def giveFunctionData(data, function):
dataRequired = []
for i in range(0, len(data)):
if data[i].__contains__(str(function)):
startIndex = i
for p in range(startIndex + 1, len(data)):
dataRequired.append(data[p])
if data[p].startswith('\n' + 'def'):
dataRequired.remove(dataRequired[len(dataRequired) - 1])
break
print(dataRequired)
return dataRequired
data = []
f = open("TestFile.py", "r")
for everyLine in f:
if not(everyLine.startswith('#') or everyLine.startswith('\n' + '#')):
data.append(everyLine)
giveFunctionData(data,'sub') # Extract content in sub() function
I expect to obtain the following result:
answer = num1 - num2
print('Difference = ',answer)
But here I get the comments written inside the function as well. Instead of the list, Is there a way to get it as it is written in the file?