Created
December 16, 2014 10:22
-
-
Save garaud/53a983f64e266368b980 to your computer and use it in GitHub Desktop.
Get the file path of a class, function or Python module as pydoc and open it into your editor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Author: Damien Garaud | |
# Date: 2014 | |
# License: Simplified BSD | |
"""Open a Python module in you editor when you're looking for a class, function | |
or module name. | |
Usage: | |
# For a module | |
> ./getmodulepath.py os.path | |
# For a function | |
> ./getmodulepath.py numpy.ones | |
# For a class | |
> ./getmodulepath.py pandas.DataFrame | |
Note: getmodulepath.py must be executable. | |
Put this in your PATH, rename it or create an alias. | |
""" | |
from __future__ import print_function | |
import sys | |
import subprocess | |
import inspect | |
import pydoc | |
EDITOR = 'emacsclient' | |
OPTIONS = '-n' | |
def _getmodule_filepath(module): | |
return inspect.getabsfile(module) | |
def _try_get_module_path(name): | |
instance, name = pydoc.resolve(name) | |
if inspect.ismodule(instance): | |
return _getmodule_filepath(instance) | |
if len(sys.argv) != 2: | |
print("Take one argument: [module/class/func] NAME") | |
sys.exit(1) | |
module_name = sys.argv[1] | |
instance, name = pydoc.resolve(module_name) | |
if inspect.ismodule(instance): | |
fpath = _getmodule_filepath(instance) | |
elif inspect.isbuiltin(instance): | |
fpath = _getmodule_filepath(inspect.getmodule(instance)) | |
else: # function or class | |
fpath = _try_get_module_path(instance.__module__) | |
print("Open '{}' with {}".format(fpath, EDITOR)) | |
subprocess.call([EDITOR, OPTIONS, fpath]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment