Helpers

Problematic

How can we avoid writing the same thing every time?

Documentation

The tool to check the availability or syntax of domain, IP or URL.

██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides the helpers.

Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Special thanks:
https://pyfunceble.github.io/special-thanks.html
Contributors:
https://pyfunceble.github.io/contributors.html
Project link:
https://github.com/funilrys/PyFunceble
Project documentation:
https://pyfunceble.readthedocs.io/en/master/
Project homepage:
https://pyfunceble.github.io/

License:

Copyright 2017, 2018, 2019, 2020 Nissar Chababy

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Command()

class PyFunceble.helpers.Command(command, encoding='utf-8')[source]

Shell command execution.

Parameters:
  • command (str) – The command to execute.
  • encoding (str) – The encoding to use to decode the shell output.
_decode_output(to_decode)[source]

Decode the output of a shell command in order to be readable.

Parameters:to_decode (bytes) – Output of a command to decode.
Returns:The decoded output.
Return type:str
execute()[source]

Execute the given command.

Returns:The output of the command.
Return type:str
run(rstrip=True)[source]

Run the given command and yield each line(s) one by one.

Note

The difference between this method and execute() is that execute() wait for the process to end in order to return its output while this method return each line one by one - as they are outputed.

Parameters:rstrip (bool) – Deactivates the rstrip of the output.
run_to_stdout()[source]

Run the given command and print each line(s) to stdout.

Dict()

class PyFunceble.helpers.Dict(main=None)[source]

Simplify some dict manipulation.

Parameters:main (dict) – The main dict to work with.
Raises:TypeError – When main is not a dict nor a list (tolarated).
classmethod from_json(json_str, return_dict_on_error=True)[source]

Converts a given JSON string to dict/list.

Parameters:return_dict_on_error (bool) – Return a dict instead of a NoneType.
Return type:dict|list
classmethod from_json_file(file_path, encoding='utf-8', return_dict_on_error=True)[source]

Reads the given file path and convert it’s content to dict/list (tolarated).

Parameters:
  • file_path (str) – The file path.
  • return_dict_on_error (bool) – Return a dict instead of a NoneType.
Return type:

dict|list

classmethod from_yaml(yaml_str)[source]

Converts the given YAML string to dict/list.

Parameters:yaml_str (str) – The YAML string to convert.
Return type:dict|list
classmethod from_yaml_file(file_path, encoding='utf-8')[source]

Converts a given YAML formatted file, into dict/list.

Parameters:
  • file_path (str) – The file path.
  • encoding (str) – The encoding to use.
Return type:

dict|list

has_same_keys_as(to_check, loop=False)[source]

A dirty solution which checks keys are presents in both given dict.

Parameters:
  • to_check (dict) – The dict to check.
  • loop (bool) – DO NOT USE, only used to tell us wen to return the list of dataset or the final result.
Return type:

bool

remove_key(key_to_remove)[source]

Remove a given key from a given dictionary.

Parameters:key_to_remove (list|str) – The key(s) to delete.
Returns:The dict without the given key(s).
Return type:dict|None
rename_key(key_to_rename, strict=True)[source]

Rename the given keys from the given dictionary.

Parameters:
  • key_to_rename (dict) –

    The key(s) to rename.

    Expected format: {old:new}

  • strict (bool) – Tell us if we have to rename the exact index or the index which looks like the given key(s)
Returns:

The well formatted dict.

Return type:

dict|None

to_json(ensure_ascii=False, indent=4, sort_keys=True)[source]

Converts a given dict to JSON and return the json string.

Parameters:
  • ensure_ascii (bool) – Avoids unicode.
  • indent (int) – The indentation to apply.
  • sort_keys – Sort the keys.
Return type:

str

to_json_file(file_path, ensure_ascii=False, indent=4, sort_keys=True, encoding='utf-8')[source]

Converts the given dict to JSON and save the result into a given file path.

Parameters:
  • file_path (str) – The file path.
  • ensure_ascii (bool) – Avoids unicode.
  • indent (int) – The indentation to apply.
  • sortkeys (bool) – Sorts the keys.
to_yaml(encoding='utf-8', default_flow_style=False, indent=4, allow_unicode=True, sort_keys=True)[source]

Converts the given dict/list to the YAML format and return the result.

Parameters:
  • encoding (str) – The encoding to use.
  • default_flow_style (bool) – Uses the default flow style.
  • indent (int) – The indentation to apply.
  • allow_unicode (bool) – Allows the decoding of unicode chars.
  • sort_keys (bool) – Sors the keys.
Return type:

dict|list

to_yaml_file(file_path, encoding='utf-8', default_flow_style=False, indent=4, allow_unicode=True, sort_keys=True)[source]

Converts the given dict/list to YAML and save the result into a file.

Parameters:
  • file_path (str) – The file path.
  • encoding (str) – The encoding.
  • default_flow_style (bool) – Uses the default flow style.
  • indent (int) – The indentation to apply.
  • allow_unicode (bool) – Allows the decoding of unicode chars.
  • sort_keys (bool) – Sorts the keys.

Directory()

class PyFunceble.helpers.Directory(dir_path=None)[source]

Simplify the directories manipulation.

:param str dir_path the path to work with.

create(dir_path=None)[source]

Creates the given directory path.

Returns:The output of self.exists after the directory creation.
Return type:bool
delete(dir_path=None)[source]

Deletes the given directory path.

Returns:not self.exists after the directory deletion.
Rtypt:bool
exists(dir_path=None)[source]

Checks if the given directory exists.

fix_path(dir_path=None, splited_path=None)[source]

Fix the path of the given path.

Note

We consider a path as fixed if it ends with the right directory separator.

classmethod get_current(with_end_sep=False)[source]

Returns the current directory path.

Parameters:with_end_sep (bool) – Add a directory separator at the end.

Download()

class PyFunceble.helpers.Download(url, verify_certificate=True)[source]

Simplification of the downloads.

Parameters:
  • url (str) – The url to download.
  • verify_certificate (bool) – Allows/Disallows the certificate verification.
text(destination=None)[source]

Download the body of the given url.

Note

if destination is set to None, we only return the output.

Otherwise, we save the output into the given destination, but we also return the output.

Parameters:

destination (str) – The download destination.

Return type:

str:

Raises:

File()

class PyFunceble.helpers.File(file_path=None)[source]

Simplify the file manipulations.

Parameters:file_path (str) – The file path to work with.
copy(destination)[source]

Copy the globaly given file path to the given destination.

Parameters:destination (str) – The destination of the copy.
delete(file_path=None)[source]

Deletes the given file path if it exists.

Parameters:file_path (str) –

The file path to check.

Note

If None is given, we report to the globally given file path.

Returns:The non existance state of the file.
Return type:bool
exists(file_path=None)[source]

Checks if the given file path exists.

Parameters:file_path (str) –

The file path to check.

Note

If None is given, we report to the globally given file path.

Return type:bool
get_size(file_path=None)[source]

Provides the size (in bytes) of the given file path.

Parameters:file_path (str) –

The file path to check.

Note

If None is given, we report to the globally given file path.

Return type:int
is_empty(file_path=None)[source]

Checks if the given file path is empty.

move(destination)[source]

Move the globally given file path to the given destination.

Parameters:destination (str) – The destination of the file.
read(file_path=None, encoding='utf-8')[source]

Read the given file path and return it’s content.

Parameters:
  • file_path (str) –

    The file path to check.

    Note

    If None is given, we report to the globally given file path.

  • encoding (str) – The encoding to use.
Return type:

str

write(data, overwrite=False, encoding='utf-8', file_path=None)[source]

Write the given data into the given file path.

Parameters:
  • data (str) – The data to write.
  • encoding (str) – The encoding to use while opening the file.
  • file_path (str) –

    The file path to check.

    Note

    If None is given, we report to the globally given file path.

Hash()

class PyFunceble.helpers.Hash(algo='sha512_224')[source]

Simplify the hashing of data or file content.

Parameters:algo (str) – The algorithm to use for hashing.
Raises:ValueError – When the given algo is not known.
data(data)[source]

Hash the given data.

Parameters:data (str, bytes) – The data to hash.
Return type:str
file(file_path, encoding='utf-8')[source]

Open the given file, and it’s content.

Parameters:file_path (str) – The file to hash.
Return type:str

List()

class PyFunceble.helpers.List(main, remove_empty=False)[source]

Simplify the list manipulation.

Parameters:
  • main (list) – The main list to work with.
  • remove_empty (bool) – Process the deletion of empty strings.
custom_format(key_method, reverse=False)[source]

Return a well formatted list. With the key_method as a function/method to format the elements before sorting.

Parameters:
  • key_method (function|method) – A function or method to use to format the readed element before sorting.
  • reverse (bool) – Tell us if we have to reverse the list.
Returns:

A sorted list.

Return type:

list

format()[source]

Return a well formatted list. Basicaly, it’s sort a list and remove duplicate.

Returns:A sorted, without duplicate, list.
Return type:list

Merge()

class PyFunceble.helpers.Merge(main)[source]

Simplify the merging of dict and list.

Parameters:main (str, tuple, bool, int, dict, list, float) – The main data to work with.
_Merge__dict(origin, strict=True)

Process the dict merging.

Parameters:strict (bool) – Activates the strict mode.
Return type:dict
_Merge__list(origin, strict=True)

Process the list merging.

Parameters:strict (bool) – Activates the strict mode.
Return type:list
into(origin, strict=True)[source]

Process the mergin.

Parameters:
  • origin – The original data.
  • strict (bool) – Activates the strict mode.

Regex()

class PyFunceble.helpers.Regex(regex, escape=False)[source]

Simplify the regex matching and usage.

Parameters:
  • regex (str) – The regex to use.
  • escape (bool) – Escapes the given regex.
get_matching_list(data)[source]

Returns the strings which does the match the regex in the given data.

get_not_matching_list(data)[source]

Returns the strings which does not the match the regex in the given data.

match(data, rematch=False, group=0, return_match=True)[source]

Checks if the given data match the given regex string.

Parameters:
  • data (str) – The data to work with.
  • rematch (bool) –

    The equivalent of the $BASH_REMATCH but in Python.

    It’s basically a list of all groups.

  • group (bool) – The group to return when return_match is set to True.
  • return_match (bool) – Return the part that match the given regex string.
replace_match(data, replacement, occurences=0, multiline=False)[source]

Replaces the string which match the regex string with the given replacement.

Parameters:
  • data (str) – The data to work with.
  • replacement (str) – The replacement of the matched regex.
  • occurences (int) –

    The number of occurences to replace.

    Note

    0 means all occurences.

Return type:

str