pawnlib.input package

from pawnlib.input import *

Submodules

pawnlib.input.prompt

from pawnlib.input import prompt
class PromptWithArgument(argument='', min_length=1, max_length=1000, verbose=1, **kwargs)[source]

Bases: object

fuzzy(*args, **kwargs)[source]
prompt(*args, **kwargs)[source]
checkbox(*args, **kwargs)[source]
select(*args, **kwargs)[source]
class CompareValidator(operator='>=', length=0, message='Input should be a ', float_allowed=False, value_type='number', min_value=0, max_value=0)[source]

Bases: NumberValidator

Validator that compares the input value with the given operator and length.

Parameters:
  • operator (Literal["!=", "==", ">=", "<=", ">", "<"]) – Comparison operator. Allowed operators are ‘!=’, ‘==’, ‘>=’, ‘<=’, ‘>’, and ‘<’. |default| '>='

  • length (int) – Length of the input value. |default| 0

  • message (str) – Error message to display when the validation fails. |default| 'Input should be a '

  • float_allowed (bool) – Flag to allow float input values. |default| False

  • value_type (str) – Type of the input value. Allowed types are ‘number’, ‘string’, and ‘min_max’. |default| 'number'

  • min_value (int) – Minimum value for ‘min_max’ value type. |default| 0

  • max_value (int) – Maximum value for ‘min_max’ value type. |default| 0

Example

validator = CompareValidator(
    operator=">=",
    length=3,
    message="Input should be a number greater than or equal to 3",
    float_allowed=True,
    value_type="number",
    min_value=3
)

validator.validate(document)
raise_error(document, message='')[source]

Raises a ValidationError with the given error message.

Parameters:
  • document (Any) – The document being validated.

  • message (str) – The error message to display. |default| ''

validate(document)[source]

Validates the input document.

Parameters:

document (Any) – The document to validate.

Return type:

None

class NumberCompareValidator(operator='', length=0, message='Input should be a ', float_allowed=False)[source]

Bases: CompareValidator

A validator that compares a number with a given operator.

Parameters:
  • operator (optional) – A string representing the operator. Default is “”. |default| ''

  • length (int, optional) – An integer representing the length of the input. Default is 0. |default| 0

  • message (str, optional) – A string representing the error message. Default is “Input should be a “. |default| 'Input should be a '

  • float_allowed (bool, optional) – A boolean representing whether float input is allowed. Default is False. |default| False

Example

validator = NumberCompareValidator(operator=">", length=0, message="Input should be a number", float_allowed=True)
validator.validate(5) # >> True
validator.validate("5.0") # >> True
validator.validate("abc") # >> False
class StringCompareValidator(operator='', length=0, message='Input should be a ', float_allowed=False)[source]

Bases: CompareValidator

A validator that compares a string with a given operator.

Parameters:
  • operator (optional) – A string representing the operator. Default is “”. |default| ''

  • length (int, optional) – An integer representing the length of the input. Default is 0. |default| 0

  • message (str, optional) – A string representing the error message. Default is “Input should be a “. |default| 'Input should be a '

  • float_allowed (bool, optional) – A boolean representing whether float input is allowed. Default is False. |default| False

Example

validator = StringCompareValidator(operator=">", length=0, message="Input should be a string", float_allowed=False)
validator.validate("abc") # >> True
validator.validate(123) # >> False
validator.validate("abcdefg") # >> False
class MinMaxValidator(min_value=0, max_value=0, message='Input should be a ', float_allowed=False)[source]

Bases: CompareValidator

A validator that checks whether a number is within a given range.

Parameters:
  • min_value (int, optional) – An integer representing the minimum value. Default is 0. |default| 0

  • max_value (int, optional) – An integer representing the maximum value. Default is 0. |default| 0

  • message (str, optional) – A string representing the error message. Default is “Input should be a “. |default| 'Input should be a '

  • float_allowed (bool, optional) – A boolean representing whether float input is allowed. Default is False. |default| False

Example

validator = MinMaxValidator(min_value=0, max_value=10, message="Input should be between 0 and 10", float_allowed=True)
validator.validate(5) # >> True
validator.validate(15) # >> False
validator.validate("5.0") # >> True
validator.validate("abc") # >> False
class HexValidator(message='Input should be a ', allow_none=False, value_type='Hex', value_length=1)[source]

Bases: CompareValidator

validate(document)[source]

Validates whether the input is a valid Hex.

Parameters:

document (Any) – The input to validate.

Raises:

ValueError – If the input is not a valid private key.

Return type:

None

Example

validator = HexValidator(value_type="TX hash", value_length=64)
validator.validate("4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d")
# >> None
class PrivateKeyValidator(message='Input should be a ', allow_none=False)[source]

Bases: CompareValidator

Validator class for private key.

Parameters:
  • message (str) – Error message to display. |default| 'Input should be a '

  • allow_none (bool) – If True, allows None as a valid input. |default| False

Example

validator = PrivateKeyValidator()
validator.validate("4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d")
# >> None
validate(document)[source]

Validates whether the input is a valid private key.

Parameters:

document (Any) – The input to validate.

Raises:

ValueError – If the input is not a valid private key.

Return type:

None

Example

validator = PrivateKeyValidator()
validator.validate("4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d")
# >> None
class PrivateKeyOrJsonValidator(message='Input should be a ', allow_none=False)[source]

Bases: CompareValidator

Validator class for private key or JSON.

Parameters:
  • message (str) – Error message to display. |default| 'Input should be a '

  • allow_none (bool) – If True, allows None as a valid input. |default| False

Example

validator = PrivateKeyOrJsonValidator()
validator.validate('{"private_key": "4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d"}')
# >> None
validate(document)[source]

Validates whether the input is a valid private key or JSON.

Parameters:

document (Any) – The input to validate.

Raises:

ValueError – If the input is not a valid private key or JSON.

Return type:

None

Example

validator = PrivateKeyOrJsonValidator()
validator.validate('{"private_key": "4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d"}')
# >> None
class JsonValidator(message='Input should be a ', allow_none=False)[source]

Bases: CompareValidator

Validator class for JSON.

Parameters:
  • message (str) – Error message to display. |default| 'Input should be a '

  • allow_none (bool) – If True, allows None as a valid input. |default| False

Example

validator = JsonValidator()
validator.validate('{"private_key": "4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d"}')
# >> None
validate(document)[source]

Validates whether the input is a valid JSON.

Parameters:

document (Any) – The input to validate.

Raises:

ValueError – If the input is not a valid JSON.

Return type:

None

Example

validator = JsonValidator()
validator.validate('{"private_key": "4a3c6a7b9d9a51f4e8a46e8b8d2a6f3c2f2b7e3e8b75a8c9e7d6f5a4c3b2a19d"}')
# >> None
check_valid_private_length(text)[source]

Check if the length of a private key is valid.

Parameters:

text – a string representing a private key.

Returns:

True if the length of the private key is valid, False otherwise.

Example

check_valid_private_length("0x1234567890123456789012345678901234567890123456789012345678901234")
# >> True

check_valid_private_length("0x123456789012345678901234567890123456789012345678901234567890")
# >> False
get_operator_truth(inp, relate, cut)[source]

Compare two values based on a relationship operator.

Parameters:
  • inp (any) – First value to compare.

  • relate (str) – Relationship operator.

  • cut (any) – Second value to compare.

Returns:

Comparison result.

Return type:

bool

Example

get_operator_truth(3, '>', 2)
# >> True

get_operator_truth('hello', 'include', 'he')
# >> True
prompt_with_keyboard_interrupt(*args, **kwargs)[source]

Handle keyboard interrupt with prompt.

Parameters:
  • args

  • kwargs

Returns:

Example

prompt_with_keyboard_interrupt({'name': 'test'}, {})
# >> {'test': 'value'}

prompt_with_keyboard_interrupt([{'name': 'test'}], {})
# >> 'value'
inq_prompt(*args, **kwargs)[source]

Prompt the user for input, return the name field or the first field of the answer.

Parameters:
  • args – arguments to be passed to the prompt function

  • kwargs – keyword arguments to be passed to the prompt function

Returns:

the ‘name’ field of the answer, or the first field if ‘name’ does not exist

Example

inq_prompt(question="What's your name?")
# >> "John Doe"

inq_prompt(questions=[{"type": "input", "name": "username", "message": "Enter your username"}], style={'input': 'green'})
# >> "johndoe"
simple_input_prompt(name='', default='', type='input', choices=None, instruction=None, long_instruction=None, validate=None, filter=None, min_length=1, max_length=1000)[source]

A simple input prompt function.

Parameters:
  • name (optional) – The name of the input prompt. |default| ''

  • default (optional) – The default value for the input prompt. |default| ''

  • type (optional) – The type of the input prompt. |default| 'input'

  • choices (optional) – The choices for the input prompt. |default| None

  • instruction (optional) – The instruction for the input prompt. |default| None

  • long_instruction (optional) – The long instruction for the input prompt. |default| None

  • validate (optional) – The validation for the input prompt. |default| None

  • filter (optional) – The filter for the input prompt. |default| None

  • min_length (optional) – The minimum length for the input prompt. |default| 1

  • max_length (optional) – The maximum length for the input prompt. |default| 1000

Returns:

The input prompt.

Example

simple_input_prompt(
    name="Your Name", default="John Doe", type="input", choices=None,
    instruction="Please enter your name.", long_instruction="Your name will be used for personalization purposes.",
    validate=None, filter=None, min_length=1, max_length=1000)
# >> 'John Doe'

simple_input_prompt(
    name="Your Age", default="25", type="input", choices=None,
    instruction="Please enter your age.", long_instruction="Your age will be used for age verification purposes.",
    validate=None, filter=None, min_length=1, max_length=3)
# >> '25'
change_select_pattern(items)[source]

Change the select pattern of items.

Parameters:

items – The items to change the select pattern.

Returns:

The items with changed select pattern.

Example

items = {'1': 'One', '2': 'Two', '3': 'Three'}
change_select_pattern(items)
# >> [{'name': ' 0) 1 (One)', 'value': '1'}, {'name': ' 1) 2 (Two)', 'value': '2'}, {'name': ' 2) 3 (Three)', 'value': '3'}]

items = [1, 2, 3]
change_select_pattern(items)
# >> [1, 2, 3]
tk_prompt(**kwargs)[source]
fuzzy_prompt(**kwargs)[source]
fuzzy_prompt_to_argument(**kwargs)[source]
is_args_namespace()[source]
is_data_args_namespace()[source]
select_file_prompt(path='./', pattern='*', message='Select a file: ', recursive=False, **kwargs)[source]

Prompts the user to select a file from a given directory.

Parameters:
  • path (str, optional) – The directory to list files from. Default is current directory. |default| './'

  • pattern (str, optional) – The pattern to match files. Default is all files. |default| '*'

  • message (str, optional) – The message to display to the user. Default is “Select a file: “. |default| 'Select a file: '

  • recursive (bool, optional) – Whether to recursively search directories. Default is False. |default| False

  • kwargs – Additional keyword arguments.

Returns:

The selected file.

Example

select_file_prompt(path="./my_directory", pattern="*.txt", message="Select a text file: ", recursive=True)
# User is prompted with a list of .txt files in 'my_directory' and any subdirectories.
# Returns the file selected by the user.
parse_list(value)[source]

Parse a comma-separated string into a Python list.

Parameters:

value (str) – A string to be parsed into a list

Returns:

A list of parsed items or the original value if not a string

Return type:

list or any

Example

parse_list("apple, banana, orange")
# >> ['apple', 'banana', 'orange']

parse_list(42)
# >> 42
get_environment(key, default='', func='')[source]

Get the value of an environment variable, optionally applying a transformation function.

Parameters:
  • key (str) – The key of the environment variable

  • default (Any) – The default value to use if the environment variable is not set, default is an empty string |default| ''

  • func (Callable) – A function to apply to the environment variable value, default is no function (identity) |default| ''

Returns:

The value of the environment variable after applying the transformation function

Return type:

Any

Example

os.environ["EXAMPLE_VARIABLE"] = "1,2,3"

get_environment("EXAMPLE_VARIABLE")
# >> '1,2,3'

get_environment("EXAMPLE_VARIABLE", func=lambda x: x.split(','))
# >> ['1', '2', '3']

get_environment("NON_EXISTENT_VARIABLE", default="default_value")
# >> 'default_value'
json_input_prompt(default={}, message='Edit Transaction JSON')[source]

Prompts the user to edit a JSON file.

Parameters:
  • default (optional) – default JSON to be edited, default is an empty dictionary. |default| {}

  • message (optional) – message to be displayed while editing, default is “transaction”. |default| 'Edit Transaction JSON'

Example

default_json = {"key": "value"}
message = "Edit JSON"
json_input_prompt(default=default_json, message=message)
class NewlineHelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Bases: HelpFormatter

class ColoredHelpFormatter(*args, **kwargs)[source]

Bases: RawDescriptionHelpFormatter

force_adjust_parts(parts, _sep_space)[source]
format_help()[source]
class CustomArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)[source]

Bases: ArgumentParser

error(message: string)[source]

Prints a usage message incorporating the message to stderr and exits.

If you override this in a subclass, it should not return – it should either exit or raise an exception.

get_default_arguments(parser=None)[source]

Extract all default values from an ArgumentParser, including any subparsers.

Parameters:

parser (optional) – The ArgumentParser instance to extract defaults from. If None, an exception will be raised. |default| None

Return type:

dict

Returns:

A dictionary containing argument names as keys and their default values.

Raises:

ValueError – If no parser is provided.

This function iterates through the main parser’s actions to collect default values. If the parser has subparsers, it recursively collects their defaults as well.

Example:

from pawnlib.input import get_default_arguments

parser = get_parser()
defaults = get_default_arguments(parser)
pawn.console.log(defaults)
# >> {'command': None, 'file': ['/var/log/system.log'], 'base_dir': '.', 'log_type': 'console', 'log_file': None}
get_service_specific_arguments(parser=None, service_name=None)[source]

Extracts the arguments for a specific service from the argparse parser.

Parameters:
  • parser (optional) – The top-level argparse parser. |default| None

  • service_name (optional) – The name of the service to extract arguments for (‘ssh’ or ‘wallet’). |default| None

Returns:

Dictionary of argument names and their default values for the specified service.

ask_yes_no(question, default=None, console=None, yes_color='green', no_color='red', dim_color='dim white', emoji=True)[source]

Asks a yes/no question using Rich, placing the default option first and highlighting it.

Parameters:
  • question (str) – The question to ask the user.

  • default (Optional[bool]) – The default answer if the user just presses Enter. If None, user must explicitly answer. |default| None

  • console (Console, optional) – Rich Console object for printing. |default| None

  • yes_color (str, optional) – Color for the “Yes” option. Defaults to “green”. |default| 'green'

  • no_color (str, optional) – Color for the “No” option. Defaults to “red”. |default| 'red'

  • dim_color (str, optional) – Color for dimmed text. Defaults to “dim white”. |default| 'dim white'

  • emoji (bool, optional) – If True, includes emojis in the prompt. |default| True

Returns:

True if the user answers yes, False otherwise.

Return type:

bool