开发者

Parse External Methods Calls Within Python Function?

开发者 https://www.devze.com 2023-03-06 01:54 出处:网络
Given the python code: import sys import os def MyPythonMethod(value1, value2): # defining some variables

Given the python code:

import sys
import os 

def MyPythonMethod(value1, value2):
    # defining some variables 
    a = 4
    myValue = 15.65
    listValues = [4, 67, 83, -23]

    # check if a file exists
    if ( o开发者_如何学JAVAs.path.exists('/home/hello/myfile.txt') ):
        pass

    # doing some operation on the list
    listValues[0] = listValues[1]       

    # check if a file exists
    print sys.path

    # looping through the values
    for i in listValues:
        print i 

How can I extract the names of all external methods in function MyPythonMethod?

Ideally, I'd like to get a list of all external methods/members that are being invoked.

For MyPythonMethod, this will return:

moduleNames = ["os", "sys"]

methodsInvoked = ["os.path.exists", "sys.path"]

(yes, I know that 'path' is a member of sys, not a method; but I think you get the idea).

Any ideas?


You can't ever fully know what functions (and in your case we're talking about plain functions, not methods, since methods are member functions of a class), a function will call without parsing it, because it might do so dynamically and their names may depend on what is imported into the global namespace when the function gets called.

But you can see the module and function names that are referenced by a function by inspecting MyPythonMethod.func_code.co_names. In your case, this attribute would return the tuple ('os', 'path', 'exists', 'sys').

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号