問題描述
Атрымаць шлях выканання кансольнага скрыпта Python (Get the runpath of a python console‑script)
Short of it ‑ I need to get a console_script to return to me its current run path, so that I can override modules it is using at run time.
Here is my basic setup (summarized as best I could):
package_1:
caller_module.py
console_script_module:
main.py
dir_of_modules_to_use/
a.py
b.py
c.py
setup.py
setup.py contents:
setup(
entry_points = {
'console_scripts': [
'console‑script‑module = console_script_module.main:main'
]
}
)
Longer detail: So caller_module.py calls console‑script‑module by issuing a subprocess call. In turn the modules seen in dir_of_modules_to_use are run. I would like to provide my own version of those modules by overriding them right before this happens through a separate script. In order to do this I need to know the run path of where console‑script‑module has been installed as it is not consistent (changes in virtualenv's for example).
I tried adding this in to main.py and using a separate command line argument to call it:
def print_absoulute_dir():
print os.path.abspath('dir_of_modules_to_use')
Unfortunately this only returns the path of wherever I make the call to the console script.
DISCLAIMER ‑ this is hacky and awful I know, it's from code I inherited and I just need something working in the short term. I unfortunately cannot change the code within caller_module.py at this time, otherwise I would just change how it is calling console_script_module:main.py.
‑‑‑‑‑
參考解法
方法 1:
I'm not sure if i really understand what you want, but every python module has the __file__
attribute, which contains its location in the filesystem, and you can use sys.path to modify python module search path
import urllib
import sys
print urllib.__file__
print sys.path
(by rikityplikity、Christian Thieme)