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?

2
  • 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. Commented Feb 2, 2022 at 8:13
  • Does this answer your question? How to import a module given the full path? Commented Feb 2, 2022 at 8:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
1

Use import as you would with built-in modules:

import file as f

print(dir(f))

2 Comments

The path of the file isn' certain, it is passed in as a argument while executing the main file like python3 main.py /path/to/file so this woudn't work.
@AnonymousDebug you're right, i misread the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.