Search code examples
pythonargparse

using one py file in another via it's path


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?


Solution

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