0

I want to give a path in the command argument while running main.py, and the main.py should display all the functions that are present in the .py file mentioned in the path.

main.py

getpathfromargument = /some/path/file.py
print(functions_present_in(getpathfromargument)

the path not necessarily be in the same directory as main.py

I might run this as follows

$python main.py /some/path/file.py

to access the function from main.py do I have to import the file in the path?

  • To print methods or attributes available in a class you can use `dir`. For example, if your class name is `MyRandomClass`, then `dir(MyRandomClass)` will print methods in it. – iwrestledthebeartwice Feb 02 '22 at 08:13
  • Does this answer your question? [How to import a module given the full path?](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) – raphael Feb 02 '22 at 08:21

2 Answers2

1

Use import as you would with built-in modules:

import file as f

print(dir(f))
Maarten T.
  • 55
  • 8
1

If I understand your question correctly, you want to take a argument which is a path to a python file and print the functions present in that file.

I would go about doing that like:

from inspect import getmembers, isfunction
from sys import argv
from shutil import copyfile
from os import remove

def main():
    foo = argv[1] # Get the argument passed while executing the file
    copyfile(foo, "foo.py") # Copy the file passed in the CWD as foo.py
    import foo
    print(getmembers(foo, isfunction)) # Print the functions of that module
    remove("foo.py") # Remove that file
    
if __name__ == "__main__":
    main()

This will copy the file passed in to the CWD (Current Working Directory), import it and print the functions inside it and then remove the copy of the file which was just made in the CWD.

  • That is so cool! Thank you very much. Also, my problem should have been addressed by using a dir() but it also gives builtin functions in the list. If there was a way to modify dir() so that it gives only user defined functions that would be great. One way I see is iterating through the list and removing if it starts with "__". Would love to hear what you think. – recursiveiterator Feb 02 '22 at 08:55
  • @recursiveiterator If the module doesn't have alot of functions then it may be better to use that, but if the module has good amount of functions then I would personally use this because iterating through them would be slow. – Vaibhav Dhiman Feb 02 '22 at 09:00