INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set logger level and format. | def set_log_level_format(level, format):
"""
Set logger level and format.
:param level: logging level; see the :py:mod:`logging` constants.
:type level: int
:param format: logging formatter format string
:type format: str
"""
formatter = logging.Formatter(fmt=format)
logger.handlers... |
Given the username of a PyPI user return a list of all of the user s projects from the XMLRPC interface. | def _pypi_get_projects_for_user(username):
"""
Given the username of a PyPI user, return a list of all of the user's
projects from the XMLRPC interface.
See: https://wiki.python.org/moin/PyPIXmlRpc
:param username: PyPI username
:type username: str
:return: list of string project names
... |
Main entry point | def main(args=None):
"""
Main entry point
"""
# parse args
if args is None:
args = parse_args(sys.argv[1:])
# set logging level
if args.verbose > 1:
set_log_debug()
elif args.verbose == 1:
set_log_info()
outpath = os.path.abspath(os.path.expanduser(args.out_... |
Generate the graph ; return a 2 - tuple of strings script to place in the head of the HTML document and div content for the graph itself. | def generate_graph(self):
"""
Generate the graph; return a 2-tuple of strings, script to place in the
head of the HTML document and div content for the graph itself.
:return: 2-tuple (script, div)
:rtype: tuple
"""
logger.debug('Generating graph for %s', self._gr... |
Add a line along the top edge of a Patch in a stacked Area Chart ; return the new Glyph for addition to HoverTool. | def _line_for_patches(self, data, chart, renderer, series_name):
"""
Add a line along the top edge of a Patch in a stacked Area Chart; return
the new Glyph for addition to HoverTool.
:param data: original data for the graph
:type data: dict
:param chart: Chart to add the... |
Get s list of dates (: py: class: datetime. datetime ) present in cache beginning with the longest contiguous set of dates that isn t missing more than one date in series. | def _get_cache_dates(self):
"""
Get s list of dates (:py:class:`datetime.datetime`) present in cache,
beginning with the longest contiguous set of dates that isn't missing
more than one date in series.
:return: list of datetime objects for contiguous dates in cache
:rtyp... |
Return True if the specified cache record has no data False otherwise. | def _is_empty_cache_record(self, rec):
"""
Return True if the specified cache record has no data, False otherwise.
:param rec: cache record returned by :py:meth:`~._cache_get`
:type rec: dict
:return: True if record is empty, False otherwise
:rtype: bool
"""
... |
Return cache data for the specified day ; cache locally in this class. | def _cache_get(self, date):
"""
Return cache data for the specified day; cache locally in this class.
:param date: date to get data for
:type date: datetime.datetime
:return: cache data for date
:rtype: dict
"""
if date in self.cache_data:
log... |
Like: py: meth: ~. _column_value but collapses two unknowns into one. | def _compound_column_value(k1, k2):
"""
Like :py:meth:`~._column_value` but collapses two unknowns into one.
:param k1: first (top-level) value
:param k2: second (bottom-level) value
:return: display key
:rtype: str
"""
k1 = ProjectStats._column_value(k1)... |
If ver is a dot - separated string with at least ( num_components + 1 ) components return only the first two. Else return the original string. | def _shorten_version(ver, num_components=2):
"""
If ``ver`` is a dot-separated string with at least (num_components +1)
components, return only the first two. Else return the original string.
:param ver: version string
:type ver: str
:return: shortened (major, minor) ver... |
Return download data by version. | def per_version_data(self):
"""
Return download data by version.
:return: dict of cache data; keys are datetime objects, values are
dict of version (str) to count (int)
:rtype: dict
"""
ret = {}
for cache_date in self.cache_dates:
data = sel... |
Return download data by file type. | def per_file_type_data(self):
"""
Return download data by file type.
:return: dict of cache data; keys are datetime objects, values are
dict of file type (str) to count (int)
:rtype: dict
"""
ret = {}
for cache_date in self.cache_dates:
data... |
Return download data by installer name and version. | def per_installer_data(self):
"""
Return download data by installer name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of installer name/version (str) to count (int).
:rtype: dict
"""
ret = {}
for cache_date in sel... |
Return download data by python impelementation name and version. | def per_implementation_data(self):
"""
Return download data by python impelementation name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of implementation name/version (str) to count (int).
:rtype: dict
"""
ret = {}
... |
Return download data by system. | def per_system_data(self):
"""
Return download data by system.
:return: dict of cache data; keys are datetime objects, values are
dict of system (str) to count (int)
:rtype: dict
"""
ret = {}
for cache_date in self.cache_dates:
data = self._... |
Return download data by country. | def per_country_data(self):
"""
Return download data by country.
:return: dict of cache data; keys are datetime objects, values are
dict of country (str) to count (int)
:rtype: dict
"""
ret = {}
for cache_date in self.cache_dates:
data = sel... |
Return download data by distro name and version. | def per_distro_data(self):
"""
Return download data by distro name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of distro name/version (str) to count (int).
:rtype: dict
"""
ret = {}
for cache_date in self.cache_d... |
Return the number of downloads per day averaged over the past 7 days of data. | def downloads_per_day(self):
"""
Return the number of downloads per day, averaged over the past 7 days
of data.
:return: average number of downloads per day
:rtype: int
"""
count, num_days = self._downloads_for_num_days(7)
res = ceil(count / num_days)
... |
Return the number of downloads in the last 7 days. | def downloads_per_week(self):
"""
Return the number of downloads in the last 7 days.
:return: number of downloads in the last 7 days; if we have less than
7 days of data, returns None.
:rtype: int
"""
if len(self.cache_dates) < 7:
logger.error("Only... |
Given a number of days of historical data to look at ( starting with today and working backwards ) return the total number of downloads for that time range and the number of days of data we had ( in cases where we had less data than requested ). | def _downloads_for_num_days(self, num_days):
"""
Given a number of days of historical data to look at (starting with
today and working backwards), return the total number of downloads
for that time range, and the number of days of data we had (in cases
where we had less data than... |
Get our projectId from the GOOGLE_APPLICATION_CREDENTIALS creds JSON file. | def _get_project_id(self):
"""
Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds
JSON file.
:return: project ID
:rtype: str
"""
fpath = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None)
if fpath is None:
raise Exception(... |
Connect to the BigQuery service. | def _get_bigquery_service(self):
"""
Connect to the BigQuery service.
Calling ``GoogleCredentials.get_application_default`` requires that
you either be running in the Google Cloud, or have the
``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the path
to a c... |
Get a list of PyPI downloads table ( sharded per day ) IDs. | def _get_download_table_ids(self):
"""
Get a list of PyPI downloads table (sharded per day) IDs.
:return: list of table names (strings)
:rtype: ``list``
"""
all_table_names = [] # matching per-date table names
logger.info('Querying for all tables in dataset')
... |
Return a: py: class: datetime. datetime object for the date of the data in the specified table name. | def _datetime_for_table_name(self, table_name):
"""
Return a :py:class:`datetime.datetime` object for the date of the
data in the specified table name.
:param table_name: name of the table
:type table_name: str
:return: datetime that the table holds data for
:rty... |
Run one query against BigQuery and return the result. | def _run_query(self, query):
"""
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
"""
query_request = self.service.jobs()
... |
Return the timestamp for the newest record in the given table. | def _get_newest_ts_in_table(self, table_name):
"""
Return the timestamp for the newest record in the given table.
:param table_name: name of the table to query
:type table_name: str
:return: timestamp of newest row in table
:rtype: int
"""
logger.debug(
... |
Query for download data broken down by installer for one day. | def _query_by_installer(self, table_name):
"""
Query for download data broken down by installer, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by installer; keys are project
name, values are a di... |
Query for download data broken down by system for one day. | def _query_by_system(self, table_name):
"""
Query for download data broken down by system, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by system; keys are project name,
values are a dict of sys... |
Query for download data broken down by OS distribution for one day. | def _query_by_distro(self, table_name):
"""
Query for download data broken down by OS distribution, for one day.
:param table_name: table name to query against
:type table_name: str
:return: dict of download information by distro; keys are project name,
values are a di... |
Run all queries for the given table name ( date ) and update the cache. | def query_one_table(self, table_name):
"""
Run all queries for the given table name (date) and update the cache.
:param table_name: table name to query against
:type table_name: str
"""
table_date = self._datetime_for_table_name(table_name)
logger.info('Running a... |
Return True if we have cached data for all projects for the specified datetime. Return False otherwise. | def _have_cache_for_date(self, dt):
"""
Return True if we have cached data for all projects for the specified
datetime. Return False otherwise.
:param dt: datetime to find cache for
:type dt: datetime.datetime
:return: True if we have cache for all projects for this date... |
Backfill historical data for days that are missing. | def backfill_history(self, num_days, available_table_names):
"""
Backfill historical data for days that are missing.
:param num_days: number of days of historical data to backfill,
if missing
:type num_days: int
:param available_table_names: names of available per-date... |
Run the data queries for the specified projects. | def run_queries(self, backfill_num_days=7):
"""
Run the data queries for the specified projects.
:param backfill_num_days: number of days of historical data to backfill,
if missing
:type backfill_num_days: int
"""
available_tables = self._get_download_table_ids... |
Given a dict of data such as those in: py: class: ~. ProjectStats attributes made up of: py: class: datetime. datetime keys and values of dicts of column keys to counts return a list of the distinct column keys in sorted order. | def filter_data_columns(data):
"""
Given a dict of data such as those in :py:class:`~.ProjectStats` attributes,
made up of :py:class:`datetime.datetime` keys and values of dicts of column
keys to counts, return a list of the distinct column keys in sorted order.
:param data: data dict as returned b... |
Generate the HTML for the specified graphs. | def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('Generating templated HTML')
env = Environment(
loader=PackageLoader('pypi_download_stats', 'templates'),
extensions=['jinja2.ext.l... |
Take a dictionary of data as returned by the: py: class: ~. ProjectStats per_ * _data properties return a 2 - tuple of data dict and x labels list usable by bokeh. charts. | def _data_dict_to_bokeh_chart_data(self, data):
"""
Take a dictionary of data, as returned by the :py:class:`~.ProjectStats`
per_*_data properties, return a 2-tuple of data dict and x labels list
usable by bokeh.charts.
:param data: data dict from :py:class:`~.ProjectStats` prop... |
Find the per - day average of each series in the data over the last 7 days ; drop all but the top 10. | def _limit_data(self, data):
"""
Find the per-day average of each series in the data over the last 7
days; drop all but the top 10.
:param data: original graph data
:type data: dict
:return: dict containing only the top 10 series, based on average over
the last... |
Generate a downloads graph ; append it to self. _graphs. | def _generate_graph(self, name, title, stats_data, y_name):
"""
Generate a downloads graph; append it to ``self._graphs``.
:param name: HTML name of the graph, also used in ``self.GRAPH_KEYS``
:type name: str
:param title: human-readable title for the graph
:type title: ... |
Generate download badges. Append them to self. _badges. | def _generate_badges(self):
"""
Generate download badges. Append them to ``self._badges``.
"""
daycount = self._stats.downloads_per_day
day = self._generate_badge('Downloads', '%d/day' % daycount)
self._badges['per-day'] = day
weekcount = self._stats.downloads_per... |
Generate SVG for one badge via shields. io. | def _generate_badge(self, subject, status):
"""
Generate SVG for one badge via shields.io.
:param subject: subject; left-hand side of badge
:type subject: str
:param status: status; right-hand side of badge
:type status: str
:return: badge SVG
:rtype: str... |
Generate all output types and write to disk. | def generate(self):
"""
Generate all output types and write to disk.
"""
logger.info('Generating graphs')
self._generate_graph(
'by-version',
'Downloads by Version',
self._stats.per_version_data,
'Version'
)
self._ge... |
Replaces format style phrases ( listed in the dt_exps dictionary ) with this datetime instance s information. | def datetime_format(desired_format, datetime_instance=None, *args, **kwargs):
"""
Replaces format style phrases (listed in the dt_exps dictionary)
with this datetime instance's information.
.. code :: python
reusables.datetime_format("Hey, it's {month-full} already!")
"Hey, it's March... |
Create a DateTime object from a ISO string | def datetime_from_iso(iso_string):
"""
Create a DateTime object from a ISO string
.. code :: python
reusables.datetime_from_iso('2017-03-10T12:56:55.031863')
datetime.datetime(2017, 3, 10, 12, 56, 55, 31863)
:param iso_string: string of an ISO datetime
:return: DateTime object
... |
Get a current DateTime object. By default is local. | def now(utc=False, tz=None):
"""
Get a current DateTime object. By default is local.
.. code:: python
reusables.now()
# DateTime(2016, 12, 8, 22, 5, 2, 517000)
reusables.now().format("It's {24-hour}:{min}")
# "It's 22:05"
:param utc: bool, default False, UTC time not ... |
Cross platform compatible subprocess with CompletedProcess return. | def run(command, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=None, copy_local_env=False, **kwargs):
"""
Cross platform compatible subprocess with CompletedProcess return.
No formatting or encoding is performed on the output of subprocess, so it's
output will appear the s... |
Run a set of iterables to a function in a Threaded or MP Pool. | def run_in_pool(target, iterable, threaded=True, processes=4,
asynchronous=False, target_kwargs=None):
""" Run a set of iterables to a function in a Threaded or MP Pool.
.. code: python
def func(a):
return a + a
reusables.run_in_pool(func, [1,2,3,4,5])
# [1... |
View a dictionary as a tree. | def tree_view(dictionary, level=0, sep="| "):
"""
View a dictionary as a tree.
"""
return "".join(["{0}{1}\n{2}".format(sep * level, k,
tree_view(v, level + 1, sep=sep) if isinstance(v, dict)
else "") for k, v in dictionary.items()]) |
Turn the Namespace and sub Namespaces back into a native python dictionary. | def to_dict(self, in_dict=None):
"""
Turn the Namespace and sub Namespaces back into a native
python dictionary.
:param in_dict: Do not use, for self recursion
:return: python dictionary of this Namespace
"""
in_dict = in_dict if in_dict else self
out_dic... |
Return value of key as a list | def list(self, item, default=None, spliter=",", strip=True, mod=None):
""" Return value of key as a list
:param item: key of value to transform
:param mod: function to map against list
:param default: value to return if item does not exist
:param spliter: character to split str ... |
Download a given URL to either file or memory | def download(url, save_to_file=True, save_dir=".", filename=None,
block_size=64000, overwrite=False, quiet=False):
"""
Download a given URL to either file or memory
:param url: Full url (with protocol) of path to download
:param save_to_file: boolean if it should be saved to file or not
... |
Provide a list of IP addresses uses socket. getaddrinfo | def url_to_ips(url, port=None, ipv6=False, connect_type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP, flags=0):
"""
Provide a list of IP addresses, uses `socket.getaddrinfo`
.. code:: python
reusables.url_to_ips("example.com", ipv6=True)
# ['2606:2800:220:1:248:1893:25c8:194... |
Resolve a hostname based off an IP address. | def ip_to_url(ip_addr):
"""
Resolve a hostname based off an IP address.
This is very limited and will
probably not return any results if it is a shared IP address or an
address with improperly setup DNS records.
.. code:: python
reusables.ip_to_url('93.184.216.34') # example.com
... |
Create a background thread for httpd and serve forever | def start(self):
"""Create a background thread for httpd and serve 'forever'"""
self._process = threading.Thread(target=self._background_runner)
self._process.start() |
Returns a set up stream handler to add to a logger. | def get_stream_handler(stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Returns a set up stream handler to add to a logger.
:param stream: which stream to use, defaults to sys.stderr
:param level: logging level to set handler at
:param log_format:... |
Set up a file handler to add to a logger. | def get_file_handler(file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read,
handler=logging.FileHandler,
**handler_kwargs):
"""
Set up a file handler to add to a logger.
:param file_path: file to write the log to, defaults t... |
Grabs the specified logger and adds wanted handlers to it. Will default to adding a stream handler. | def setup_logger(module_name=None, level=logging.INFO, stream=sys.stderr,
file_path=None, log_format=log_formats.easy_read,
suppress_warning=True):
"""
Grabs the specified logger and adds wanted handlers to it. Will
default to adding a stream handler.
:param module_nam... |
Addes a newly created stream handler to the specified logger | def add_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created stream handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param stream: which stream to u... |
Addes a newly created file handler to the specified logger | def add_file_handler(logger=None, file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to lo... |
Adds a rotating file handler to the specified logger. | def add_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
max_bytes=10*sizes.mb, backup_count=5,
**handler_kwargs):
""" Adds a rotating ... |
Adds a timed rotating file handler to the specified logger. Defaults to weekly rotation with 5 backups. | def add_timed_rotating_file_handler(logger=None, file_path="out.log",
level=logging.INFO,
log_format=log_formats.easy_read,
when='w0', interval=1, backup_count=5,
**handler_kwa... |
Remove only stream handlers from the specified logger | def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... |
Remove only file handlers from the specified logger. Will go through and close each handler for safety. | def remove_file_handlers(logger=None):
"""
Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.get... |
Safely remove all handlers from the logger | def remove_all_handlers(logger=None):
"""
Safely remove all handlers from the logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
remove_file_handlers(logger)
logger.handle... |
Go through the logger and handlers and update their levels to the one specified. | def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
... |
Find the names of all loggers currently registered | def get_registered_loggers(hide_children=False, hide_reusables=False):
"""
Find the names of all loggers currently registered
:param hide_children: only return top level logger names
:param hide_reusables: hide the reusables loggers
:return: list of logger names
"""
return [logger for logg... |
Wrapper. Makes sure the function s return value has not been returned before or else it run with the same inputs again. | def unique(max_retries=10, wait=0, alt_return="-no_alt_return-",
exception=Exception, error_text=None):
"""
Wrapper. Makes sure the function's return value has not been returned before
or else it run with the same inputs again.
.. code: python
import reusables
import random
... |
Wrapper. Simple wrapper to make sure a function is only run once at a time. | def lock_it(lock=g_lock):
"""
Wrapper. Simple wrapper to make sure a function is only run once at a time.
.. code: python
import reusables
import time
def func_one(_):
time.sleep(5)
@reusables.lock_it()
def func_two(_):
time.sleep(5)
... |
Wrapper. Time the amount of time it takes the execution of the function and print it. | def time_it(log=None, message=None, append=None):
"""
Wrapper. Time the amount of time it takes the execution of the function
and print it.
If log is true, make sure to set the logging level of 'reusables' to INFO
level or lower.
.. code:: python
import time
import reusables
... |
Wrapper. Instead of returning the result of the function add it to a queue. | def queue_it(queue=g_queue, **put_args):
"""
Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
... |
Wrapper. Log the traceback to any exceptions raised. Possible to raise custom exception. | def log_exception(log="reusables", message=None, exceptions=(Exception, ),
level=logging.ERROR, show_traceback=True):
"""
Wrapper. Log the traceback to any exceptions raised. Possible to raise
custom exception.
.. code :: python
@reusables.log_exception()
def test():
... |
If the function encounters an exception catch it and return the specified default or sent to a handler function instead. | def catch_it(exceptions=(Exception, ), default=None, handler=None):
"""
If the function encounters an exception, catch it, and
return the specified default or sent to a handler function instead.
.. code :: python
def handle_error(exception, func, *args, **kwargs):
print(f"{func.__n... |
Retry a function if an exception is raised or if output_check returns False. | def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of ex... |
Automatically detect archive type and extract all files to specified path. | def extract(archive_file, path=".", delete_on_success=False,
enable_rar=False):
"""
Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# ['test_structure.zip']
reusables.extract("test_structure... |
Archive a list of files ( or files inside a folder ) can chose between | def archive(files_to_archive, name="archive.zip", archive_type=None,
overwrite=False, store=False, depth=None, err_non_exist=True,
allow_zip_64=True, **tarfile_kwargs):
""" Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz... |
Save a matrix ( list of lists ) to a file as a CSV | def list_to_csv(my_list, csv_file):
"""
Save a matrix (list of lists) to a file as a CSV
.. code:: python
my_list = [["Name", "Location"],
["Chris", "South Pole"],
["Harry", "Depth of Winter"],
["Bob", "Skull"]]
reusables.list_to_cs... |
Open and transform a CSV file into a matrix ( list of lists ). | def csv_to_list(csv_file):
"""
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param c... |
Open and load data from a JSON file | def load_json(json_file, **kwargs):
"""
Open and load data from a JSON file
.. code:: python
reusables.load_json("example.json")
# {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}}
:param json_file: Path to JSON file as string
:param kwargs: Additional arguments for the ... |
Takes a dictionary and saves it to a file as JSON | def save_json(data, json_file, indent=4, **kwargs):
"""
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
... |
Return configuration options as dictionary. Accepts either a single config file or a list of files. Auto find will search for all. cfg. config and. ini in the execution directory and package root ( unsafe but handy ). | def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options):
"""
Return configuration options as dictionary. Accepts either a single
config file or a list of files. Auto find will search for all .cfg, .config
and .ini in the execution directory and package root (unsafe but handy).
... |
Return configuration options as a Namespace. | def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... |
Internal function to return walk generator either from os or scandir | def _walk(directory, enable_scandir=False, **kwargs):
"""
Internal function to return walk generator either from os or scandir
:param directory: directory to traverse
:param enable_scandir: on python < 3.5 enable external scandir package
:param kwargs: arguments to pass to walk function
:return... |
Return a directories contents as a dictionary hierarchy. | def os_tree(directory, enable_scandir=False):
"""
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
... |
Hash a given file with md5 or any other and return the hex digest. You can run hashlib. algorithms_available to see which are available on your system unless you have an archaic python version you poor soul ). | def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... |
Walk through a file directory and return an iterator of files that match requirements. Will autodetect if name has glob as magic characters. | def find_files(directory=".", ext=None, name=None,
match_case=False, disable_glob=False, depth=None,
abspath=False, enable_scandir=False):
"""
Walk through a file directory and return an iterator of files
that match requirements. Will autodetect if name has glob as magic
ch... |
Remove all empty folders from a path. Returns list of empty directories. | def remove_empty_directories(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty folders from a path. Returns list of empty directories.
:param root_directory: base directory to start at
:param dry_run: just return a list of what w... |
Remove all empty files from a path. Returns list of the empty files removed. | def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be ... |
Check a directory for duplicates of the specified file. This is meant for a single file only for checking a directory for dups use directory_duplicates. | def dup_finder(file_path, directory=".", enable_scandir=False):
"""
Check a directory for duplicates of the specified file. This is meant
for a single file only, for checking a directory for dups, use
directory_duplicates.
This is designed to be as fast as possible by doing lighter checks
befor... |
Find all duplicates in a directory. Will return a list in that list are lists of duplicate files. | def directory_duplicates(directory, hash_type='md5', **kwargs):
"""
Find all duplicates in a directory. Will return a list, in that list
are lists of duplicate files.
.. code: python
dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures')
print(len(dups))
# 56
... |
Join multiple paths together and return the absolute path of them. If safe is specified this function will clean the path with the safe_path function. This will clean root decelerations from the path after the first item. | def join_paths(*paths, **kwargs):
"""
Join multiple paths together and return the absolute path of them. If 'safe'
is specified, this function will 'clean' the path with the 'safe_path'
function. This will clean root decelerations from the path
after the first item.
Would like to do 'safe=False... |
Join any path or paths as a sub directory of the current file s directory. | def join_here(*paths, **kwargs):
"""
Join any path or paths as a sub directory of the current file's directory.
.. code:: python
reusables.join_here("Makefile")
# 'C:\\Reusables\\Makefile'
:param paths: paths to join together
:param kwargs: 'strict', do not strip os.sep
:param... |
Returns a boolean stating if the filename is safe to use or not. Note that this does not test for legal names accepted but a more restricted set of: Letters numbers spaces hyphens underscores and periods. | def check_filename(filename):
"""
Returns a boolean stating if the filename is safe to use or not. Note that
this does not test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:retu... |
Replace unsafe filename characters with underscores. Note that this does not test for legal names accepted but a more restricted set of: Letters numbers spaces hyphens underscores and periods. | def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:... |
Replace unsafe path characters with underscores. Do NOT use this with existing paths that cannot be modified this to to help generate new clean paths. | def safe_path(path, replacement="_"):
"""
Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character ... |
Blocking request to change number of running tasks | def change_task_size(self, size):
"""Blocking request to change number of running tasks"""
self._pause.value = True
self.log.debug("About to change task size to {0}".format(size))
try:
size = int(size)
except ValueError:
self.log.error("Cannot change task ... |
Hard stop the server and sub process | def stop(self):
"""Hard stop the server and sub process"""
self._end.value = True
if self.background_process:
try:
self.background_process.terminate()
except Exception:
pass
for task_id, values in self.current_tasks.items():
... |
Get general information about the state of the class | def get_state(self):
"""Get general information about the state of the class"""
return {"started": (True if self.background_process and
self.background_process.is_alive() else False),
"paused": self._pause.value,
"stopped": self._end.value,
... |
Blocking function that can be run directly if so would probably want to specify stop_at_empty to true or have a separate process adding items to the queue. | def main_loop(self, stop_at_empty=False):
"""Blocking function that can be run directly, if so would probably
want to specify 'stop_at_empty' to true, or have a separate process
adding items to the queue. """
try:
while True:
self.hook_pre_command()
... |
Start the main loop as a background process. * nix only | def run(self):
"""Start the main loop as a background process. *nix only"""
if win_based:
raise NotImplementedError("Please run main_loop, "
"backgrounding not supported on Windows")
self.background_process = mp.Process(target=self.main_loop)
... |
Run a shell command and have it automatically decoded and printed | def cmd(command, ignore_stderr=False, raise_on_return=False, timeout=None,
encoding="utf-8"):
""" Run a shell command and have it automatically decoded and printed
:param command: Command to run as str
:param ignore_stderr: To not print stderr
:param raise_on_return: Run CompletedProcess.check_... |
Change working directories in style and stay organized! | def pushd(directory):
"""Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved directory stack
"""
directory = os.path.expanduser(directory)
_saved_paths.insert(0, os.path.abspath(os.getcwd()))
os.chdir(directory)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.