When reading a python-based software, I feel confused about a line of python code: path = sys.modules[self.__class__.__module__].__file__
.
I can guess it was trying to return the file name in class file, but I'm not very clear about the exact usage of this. I saved the related code segment into a file named test.py
and I'm trying to test it by python test.py
, but it does not print anything. How can I test this kind of file?
import os
import sys
class testloadfile:
def __init__(self, test_path=None):
if test_path is None:
path = sys.modules[self.__class__.__module__].__file__
# print path
path = os.path.abspath(os.path.join(path, os.pardir))
# print path
path = os.path.join(path, "test.r")
print(path)
test_path = path
print("r file loaded")
main
routine" that a command-line(!) execution ofpython
would be expected to pick-up on. Here, you define "a class," and you define a constructor for that class, and it seems that you've also tossed-in aprint
statement, but I don't see anything here that tellspython
what is supposed to be done when this.py
file is executed from the command line. Therefore, I'm not surprised that it does nothing. :-) "Go thee now, and take a look," at some existing Python (library) code. Notice what they do, and do thee likewise.sys.modules[self.__class__.__module__].__file__
should just give you__file__
...print
? Is it part of theclass
definition or part of the__init__()
method—because as posted it's an indentation error.print()
is part of theclass
definition (and not part of the__init__()
method), running the script will execute it when the class definition executes. Regardless, it looks like @mgilson is correct, it's just an convoluted way to get__file__
.