Situation: We know that the below will check if the script has been called directly.
if __name__ == '__main__':
print "Called directly"
else:
print "Imported by other python files"
Problem: The else
clause is only a generic one and will run as long as the script was not called directly.
Question: Is there any way to get which file it was imported in, if it is not called directly?
Additional information: Below is an example of how I envisioned the code would be like, just that I do no know what to put in <something>
.
if __name__ == '__main__':
print "Called directly"
elif <something> == "fileA.py":
print "Called from fileA.py"
elif <something> == "fileB.py":
print "Called from fileB.py"
else:
print "Called from other files"
Try this:-
import sys
print sys.modules['__main__'].__file__
Refer for better answer:- How to get filename of the __main__ module in Python?
There are a couple different methods you may like to be aware of depending on what you're trying to accomplish.
The inspect
module has a getfile()
function which can be used to determine the name of the currently-executing function.
Example:
#!/usr/bin/env python3
import inspect
print(inspect.getfile(inspect.currentframe()))
Result:
test.py
To find out which command-line arguments were used to execute a script, you'll need to use sys.argv
Example:
#!/usr/bin/env python3
import sys
print(sys.argv)
Result when invoked with ./test.py a b c
:
['./test.py', 'a', 'b', 'c']
Result when invoked with python3 test.py a b c
:
['test.py', 'a', 'b', 'c']
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With