Python get current package name

How do I get the current ‘package’ name? (setup.py)

That option did work. So I returned to the ast solution I referenced in the question, and got this second pass to work:

def parse_package_name_from_setup_py(setup_py_file_name): with open(setup_py_file_name, 'rt') as f: parsed_setup_py = ast.parse(f.read(), 'setup.py') # Assumes you have an `if __name__ == '__main__'` block: main_body = next(sym for sym in parsed_setup_py.body[::-1] if isinstance(sym, ast.If)).body setup_call = next(sym.value for sym in main_body[::-1] if isinstance(sym, ast.Expr) and isinstance(sym.value, ast.Call) and sym.value.func.id in frozenset(('setup', 'distutils.core.setup', 'setuptools.setup'))) package_name = next(keyword for keyword in setup_call.keywords if keyword.arg == 'name' and isinstance(keyword.value, ast.Name)) # Return the raw string if it is one if isinstance(package_name.value, ast.Str): return package_name.value.s # Otherwise it's a variable defined in the `if __name__ == '__main__'` block: elif isinstance(package_name.value, ast.Name): return next(sym.value.s for sym in main_body if isinstance(sym, ast.Assign) and isinstance(sym.value, ast.Str) and any(target.id == package_name.value.id for target in sym.targets) ) else: raise NotImplemented('Package name extraction only built for raw strings & ' 'assigment in the same scope that setup() is called') 

Third pass (works for both installed and development versions):

# Originally from https://stackoverflow.com/a/56032725; # but made more concise and added support whence source class App(object): def get_app_name(self) -> str: # Iterate through all installed packages and try to find one # that has the app's file in it app_def_path = inspect.getfile(self.__class__) with suppress(FileNotFoundError): return next( (dist.project_name for dist in pkg_resources.working_set if any(app_def_path == path.normpath(path.join(dist.location, r[0])) for r in csv.reader(dist.get_metadata_lines('RECORD')))), None) or parse_package_name_from_setup_py( get_first_setup_py(path.dirname(__file__))) 

Not entirely sure what the larger goal is, but maybe you could be interested in reading about importlib.resources as well as importlib.metadata .

Читайте также:  Read from dictionary python

Something like the following:

import importlib.metadata import importlib.resources version = importlib.metadata.version('SomeProject') data = importlib.resources.files('top_level_package.sub_package').joinpath('file.txt').read_text() 

And more generally, it is near impossible (or not worth the amount of work) to 100% reliably detect the name of the project ( SomeProject ) from within the code. It is easier to just hard-code it.

Nevertheless here are some techniques, and ideas to retrieve the name of the project from one of its modules:

I believe some function like the following should return the name of the installed distribution containing the current file:

import pathlib import importlib_metadata def get_project_name(): for dist in importlib_metadata.distributions(): try: relative = pathlib.Path(__file__).relative_to(dist.locate_file('')) except ValueError: pass else: if relative in dist.files: return dist.metadata['Name'] return None 

Update (February 2021):

Looks like this could become easier thanks to the newly added packages_distributions() function in importlib_metadata :

  • How can I get Atom’s script package to run a script from the script’s current working directory?
  • How do I get the parent directory’s name only, not full path?
  • How to get the name of the currently active sheet in Openpyxl
  • Maya Python: How do I get the scene name but not the path or extension
  • How to get the class name of a staticmethod
  • How to get the current route with Pyramid
  • How to get the records from the current month in App Engine (Python) Datastore?
  • How do I get the name of a Cassandra cluster, using the Python driver?
  • In python, how do I get the full path name of «.»?
  • How to get the name of the original file from a .gz archive?
  • How do I get the name of a pytest mark for a test function?
  • How to get a class’s name from the object?
  • How to get the original name of a function after it is wrapped by function decorator?
  • How to get all the filename and filesize in current directory in Python
  • How can I get the path of the higher level directory of the current .py file in python?
  • how can get the user name of the python script during excution
  • How do I get the current PyInterpreterState?
  • how do i call the parent method if i have a function with the same name in the current class (if possible)
  • How to find the name of the current function?
  • How to get the requested file name in BaseHTTPServer in python?
  • How to sort through a list of dicitonaries and get all orders with same restaurant name without defining the restaurant name?
  • In PyQt5, How we get the name/Object name of the focus widgets?
  • How to get the name of lists for comparison purposes
  • How do I get a functions current name in python
  • how to get the url of the current page in a GAE template
  • How to get the difference between current time and 15s forward in pandas?
  • how can i get the path plus the name of the first file in a folder and so on in python
  • How to setup imports and dependencies between modules in the same python package
  • How to get the current coordinates of a sprite in pygame?
  • How to get the full class name of a sub-class with Python
  • How to get a field value from a packet layer if the field name is a string variable?
  • How to get the same name with multiple value get unique results in Python
  • how to get records into wizard from the current form view in odoo?
  • How to get files name within subfolders without the route in GCS using Python?
  • How to get the url of current tab in selenium?
  • How to get the current Linux theme with Python?
  • How to get the package description using python-apt?
  • Python — How do I get the process name of the focused window on Ubuntu?(not the window title)
  • How can I get the current read position in a win32file file handle?
  • How to get the uniform current date time throughout each loop in Airflow?
  • How to use Beautifulsoup to get the latest version of a source package
  • How to get the URL of the current webpage in python?
  • How do I get the current active tab in google chrome, using python
  • How to get the current python interpreter path
  • How can I get the file name of a tf.summary.FileWriter in TensorFlow?
  • How to get the database and table name from a ReQL query
  • Python 3.x — How to get the directory where user installed package
  • How to use python to get the current commit of its own github repository
  • Python eve — how to get the current user after successful authentication?
  • How do I get the current path of the file executing the current thread?

More Query from same tag

  • How to convert a list of numbers to a list of strings?
  • How to add custom fields to pivot view using custom model in Odoo 9.0
  • Compute uniswap pair address via python
  • Python and Redis. Why is scan_iter() so much slower than keys() with mget()?
  • Get data by pages and merge it into one using Python (pagination)
  • Dask: subset (or drop) rows from Dataframe by index
  • Pycuda Compilation Error
  • how do I convert a list into a counter object in python
  • cosine-similarity between consecutive pairs using whole articles in JSON file
  • Output a python script to text file
  • How to remove scale value from tkinter Scale widget display?
  • Dictionary from another dictionary
  • Why os.path.getsize() throw error in python?
  • Wait till download is complete in Python+Selenium+Firefox
  • How can I convert an integer into a base-256 representation?
  • Getting «ImportError: cannot import name HTTPSConnection» error in Python 2.7
  • Filtering a column in a Spark Dataframe to find percentage of each element
  • Scrapy: Running multiple spider at scrapyd — python logical error
  • Removing the remainder of a line after occurrence of a character
  • How to slice a string in Python using a dictionary containing character positions?
  • Split columns from text file into lists in python
  • Error , Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram to unpickle a file
  • How to Make Status bar widget clickable and read only openerp 7.0
  • Two contour plots in single viewer- Python FiPy
  • How can I locate python2 path within python3 code?
  • How can I use editors/IDEs with a virtual environment | python and venv?
  • pip3 not working on ubuntu 20.04: «has no attribute ‘SourceFileLoader'»
  • Splitting a string and retaining the delimiter with the delimiter appearing contiguously
  • ModuleNotFoundError: No module named ‘schedule’
  • Win 7 32 matplotlib dateutil
  • Paramiko: Asynchronous reading for long shell script output using ‘select’
  • How to use glReadPixels in Python and OpenGL?
  • How to find the repository that git hooks are running for
  • Scrape content of element with data- attribute — Python BeautifulSoup
  • How to calculate the RMSE on Ridge regression model

Источник

Get Module File Information in Python

In Python sometimes you need to figure out where a function lives on the hard disk, or what file is calling your function. The os module provides tools for getting file and directory information and the inspect module provides the ability to inspect the stack and see what module is calling your function.

Get file information about a module

The os module in Python provides many useful ways for getting the file name of where a module lives. There are functions to get file names, directory names, and get absolute paths. Check out this example:

# Example assumes this file is named test.py
# and lives in /home/nanodano/
# https://docs.python.org/3/library/os.path.html

import os

# Prints the full path of where the os.py module resides
print(os.__file__)


# The name of file where this print statement is written
print(__file__)
# test.py

# Get the full absolute path using os.path.abspath()
print(os.path.abspath(__file__))
# /home/nanodano/test.py

# Get the directory name of a file with os.path.dirname()
print(os.path.dirname(__file__))
# Relative to current directory
# Prints an empty string if being run from current directory
# Prints .. if being called from a deeper directory

# Combine to get absolute path of the directory containing the python file
print(os.path.abspath(os.path.dirname(__file__)))
# /home/nanodano

## Other functions that might be useful
# os.path.join() # Join directory names using system specific dir separator
# os.sep() # Path separator character (system specific)
# os.getcwd() # Full absolute path
# os.walk() # Generator to walk dirs recursively
# os.listdir() # Current dir or specific dir

Get module and file name of caller

In some cases, your function is getting called by code from other .py files. If you want to figure out where your function is being called from, you can inspect the stack. The inspect module provides a way to get this data.

import inspect

# Import this to other module and call it
def print_caller_info():
# Get the full stack
stack = inspect.stack()

# Get one level up from current
previous_stack_frame = stack[1]
print(previous_stack_frame.filename) # Filename where caller lives

# Get the module object of the caller
calling_module = inspect.getmodule(stack_frame[0])
print(calling_module)
print(calling_module.__file__)


if __name__ == '__main__':
print_caller_info()

Conclusion

After reading this, you should know how to get the relative and absolute filename of the current Python modules as well as modules that are calling your function.

Источник

Оцените статью