shellfish.fs.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish
⚓︎
shellfish ~ shell and file-system utils
Classes⚓︎
shellfish.Done(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
PRun => 'ProcessRun' for finished processes
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
Attributes⚓︎
shellfish.Done.__property_fields__: Set[str]
property
⚓︎
Returns a set of property names for the class that have a setter
Functions⚓︎
shellfish.Done.__contains__(key: _KT) -> bool
⚓︎
Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.Done.__ge__(filepath: FsPath) -> 'Done'
⚓︎
Operator overload for writing stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
659 660 661 662 663 664 665 666 667 668 669 670 |
|
shellfish.Done.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎
Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.Done.__getattr__(item: _KT) -> Any
⚓︎
Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.Done.__gt__(filepath: FsPath) -> None
⚓︎
Operator overload for writing a stdout to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
650 651 652 653 654 655 656 657 |
|
shellfish.Done.__irshift__(filepath: FsPath) -> 'Done'
⚓︎
Operator overload for appending stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
681 682 683 684 685 686 687 688 689 690 691 692 |
|
shellfish.Done.__post_init__() -> None
⚓︎
Write the stdout/stdout to sys.stdout/sys.stderr post object init
Source code in libs/shellfish/shellfish/sh.py
538 539 540 541 |
|
shellfish.Done.__rshift__(filepath: FsPath) -> None
⚓︎
Operator overload for appending stdout to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
672 673 674 675 676 677 678 679 |
|
shellfish.Done.__setitem__(key: _KT, value: _VT) -> None
⚓︎
Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.Done.asdict() -> Dict[_KT, Any]
⚓︎
Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.Done.check(ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0) -> None
⚓︎
Check returncode and stderr
Raises:
Type | Description |
---|---|
DoneError
|
If return code is non-zero and stderr is not None |
Source code in libs/shellfish/shellfish/sh.py
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
|
shellfish.Done.completed_process() -> CompletedProcess[str]
⚓︎
Return subprocess.CompletedProcess object
Source code in libs/shellfish/shellfish/sh.py
631 632 633 634 635 636 637 638 |
|
shellfish.Done.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎
Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.Done.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎
Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.Done.done_dict() -> DoneDict
⚓︎
Return Done object as typed-dict
Source code in libs/shellfish/shellfish/sh.py
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
|
shellfish.Done.done_obj() -> DoneObj
⚓︎
Return Done object typed dict
Source code in libs/shellfish/shellfish/sh.py
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
|
shellfish.Done.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎
Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.Done.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎
Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.Done.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.Done.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎
Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.Done.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎
Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.Done.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.Done.eject() -> Dict[_KT, _VT]
⚓︎
Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.Done.entries() -> ItemsView[_KT, _VT]
⚓︎
Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.Done.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.Done.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.Done.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.Done.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎
Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.Done.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.Done.grep(string: str) -> List[str]
⚓︎
Return lines in stdout that have
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
String to search for |
required |
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of strings of stdout lines containing the given search string |
Source code in libs/shellfish/shellfish/sh.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 |
|
shellfish.Done.has_required_fields() -> bool
classmethod
⚓︎
Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.Done.is_default() -> bool
⚓︎
Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.Done.items() -> ItemsView[_KT, _VT]
⚓︎
Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.Done.json(*args: Any, **kwargs: Any) -> str
⚓︎
Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.Done.json_parse(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
706 707 708 709 710 711 712 713 714 715 716 717 718 |
|
shellfish.Done.json_parse_stderr(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stderr
Source code in libs/shellfish/shellfish/sh.py
700 701 702 703 704 |
|
shellfish.Done.json_parse_stdout(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
694 695 696 697 698 |
|
shellfish.Done.keys() -> KeysView[_KT]
⚓︎
Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.Done.parse_json(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout (alias bc I keep flip-flopping the fn name)
Source code in libs/shellfish/shellfish/sh.py
720 721 722 723 724 725 726 727 728 |
|
shellfish.Done.recurse() -> None
⚓︎
Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.Done.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.Done.sys_print() -> None
⚓︎
Write self.stdout to sys.stdout and self.stderr to sys.stderr
Source code in libs/shellfish/shellfish/sh.py
616 617 618 619 |
|
shellfish.Done.to_dict() -> Dict[str, Any]
⚓︎
Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.Done.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.Done.to_dict_filter_none() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.Done.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.Done.to_json_dict() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.Done.to_json_obj() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.Done.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.Done.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.Done.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎
Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.Done.write_stderr(filepath: FsPath, *, append: bool = False) -> None
⚓︎
Write stderr as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
640 641 642 643 644 645 646 647 648 |
|
shellfish.Done.write_stdout(filepath: FsPath, *, append: bool = False) -> None
⚓︎
Write stdout as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
621 622 623 624 625 626 627 628 629 |
|
shellfish.DoneError(done: Done)
⚓︎
Bases: SubprocessError
Raised when run() is called with check=True and the process returns a non-zero exit status.
Attributes:
Name | Type | Description |
---|---|---|
cmd |
str
|
command that was run |
returncode |
int
|
exit status of the process |
stdout |
str
|
standard output (stdout) of the process |
stderr |
str
|
standard error (stderr) of the process |
Source code in libs/shellfish/shellfish/sh.py
462 463 464 465 466 467 468 |
|
shellfish.DoneObj
⚓︎
Bases: TypedDict
Todo
deprecate this in favor of DoneDict
shellfish.Flag
⚓︎
Flag obj
Examples:
>>> Flag.__help
'--help'
>>> Flag._v
'-v'
shellfish.FlagMeta
⚓︎
Bases: type
Meta class
Functions⚓︎
shellfish.FlagMeta.attr2flag(string: str) -> str
cached
staticmethod
⚓︎
Convert and return attr to string
Source code in libs/shellfish/shellfish/sh.py
355 356 357 358 359 |
|
shellfish.HrTime(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
High resolution time
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
Attributes⚓︎
shellfish.HrTime.__property_fields__: Set[str]
property
⚓︎
Returns a set of property names for the class that have a setter
Functions⚓︎
shellfish.HrTime.__contains__(key: _KT) -> bool
⚓︎
Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.HrTime.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎
Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.HrTime.__getattr__(item: _KT) -> Any
⚓︎
Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.HrTime.__post_init__() -> Any
⚓︎
Function place holder that is called after object initialization
Source code in libs/jsonbourne/jsonbourne/pydantic.py
98 99 |
|
shellfish.HrTime.__setitem__(key: _KT, value: _VT) -> None
⚓︎
Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.HrTime.asdict() -> Dict[_KT, Any]
⚓︎
Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.HrTime.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎
Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.HrTime.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎
Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.HrTime.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎
Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.HrTime.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎
Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.HrTime.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.HrTime.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎
Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.HrTime.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎
Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.HrTime.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.HrTime.eject() -> Dict[_KT, _VT]
⚓︎
Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.HrTime.entries() -> ItemsView[_KT, _VT]
⚓︎
Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.HrTime.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.HrTime.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.HrTime.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.HrTime.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎
Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.HrTime.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.HrTime.from_seconds(seconds: float) -> 'HrTime'
classmethod
⚓︎
Return HrTime object from seconds
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
'HrTime'
|
HrTime object |
Source code in libs/shellfish/shellfish/sh.py
417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
shellfish.HrTime.has_required_fields() -> bool
classmethod
⚓︎
Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.HrTime.is_default() -> bool
⚓︎
Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.HrTime.items() -> ItemsView[_KT, _VT]
⚓︎
Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.HrTime.json(*args: Any, **kwargs: Any) -> str
⚓︎
Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.HrTime.keys() -> KeysView[_KT]
⚓︎
Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.HrTime.recurse() -> None
⚓︎
Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.HrTime.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.HrTime.to_dict() -> Dict[str, Any]
⚓︎
Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.HrTime.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.HrTime.to_dict_filter_none() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.HrTime.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.HrTime.to_json_dict() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.HrTime.to_json_obj() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.HrTime.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.HrTime.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.HrTime.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎
Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.LIN
⚓︎
Bases: LIN
Linux (and Mac) shell commands/methods container
Functions⚓︎
shellfish.LIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
str
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
shellfish.LIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
shellfish.LIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
Allow links to already exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
|
shellfish.LIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exist_ok
|
bool
|
Allow links to already exist |
False
|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
Source code in libs/shellfish/shellfish/osfs.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
shellfish.LIN.rsync(src: str, dest: str, delete: bool = False, mkdirs: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> Done
staticmethod
⚓︎
Run an rsync
subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mkdirs
|
bool
|
Make destination directories if they do not already exist; defaults to False. |
False
|
src
|
str
|
Source directory path |
required |
dest
|
str
|
Destination directory path |
required |
delete
|
bool
|
Delete files/directories in destination if they do exist in source |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Name | Type | Description |
---|---|---|
Done |
Done
|
Done object containing the info for the rsync run |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 |
|
shellfish.LIN.rsync_args(src: str, dest: str, delete: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> List[str]
staticmethod
⚓︎
Return args for rsync command on linux/mac
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to remote (raid) tdir |
required |
dest
|
str
|
path to local tdir |
required |
delete
|
bool
|
Flag that will do a 'hard sync' |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from rsync |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 |
|
shellfish.LIN.unlink_dir(link: str) -> None
staticmethod
⚓︎
Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
133 134 135 136 137 138 139 140 141 |
|
shellfish.LIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
143 144 145 146 147 148 149 150 151 152 |
|
shellfish.LIN.unlink_file(link: str) -> None
staticmethod
⚓︎
Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
154 155 156 157 158 159 160 161 162 |
|
shellfish.LIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
164 165 166 167 168 169 170 171 172 173 |
|
shellfish.Stdio
⚓︎
Bases: IntEnum
Standard-io enum object
shellfish.WIN
⚓︎
Bases: WIN
Windows shell commands/methods container
Functions⚓︎
shellfish.WIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
shellfish.WIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link(s) exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
shellfish.WIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
shellfish.WIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
shellfish.WIN.robocopy(src: str, dest: str, *, mkdirs: bool = True, delete: bool = False, exclude_files: Optional[Iterable[str]] = None, exclude_dirs: Optional[Iterable[str]] = None, dry_run: bool = False) -> Done
staticmethod
⚓︎
Robocopy wrapper function (crude in that it opens a subprocess)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
mkdirs
|
bool
|
Flag to make destinaation directories if they do not already exist |
True
|
Returns:
Type | Description |
---|---|
Done
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 |
|
shellfish.WIN.robocopy_args(src: str, dest: str, *, delete: bool = False, exclude_files: Optional[List[str]] = None, exclude_dirs: Optional[List[str]] = None, dry_run: bool = False) -> List[str]
staticmethod
⚓︎
Return list of robocopy command args
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[List[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[List[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 |
|
shellfish.WIN.unlink_dir(link: str) -> None
staticmethod
⚓︎
Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
269 270 271 272 273 274 275 276 277 278 279 280 |
|
shellfish.WIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.WIN.unlink_file(link: str) -> None
staticmethod
⚓︎
Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
298 299 300 301 302 303 304 305 306 307 308 309 |
|
shellfish.WIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
Functions⚓︎
shellfish.basename(fspath: FsPath) -> str
⚓︎
Return the basename of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 |
|
shellfish.cd(dirpath: FsPath) -> None
⚓︎
Change directory to given dirpath; alias for os.chdir
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory fspath |
required |
Source code in libs/shellfish/shellfish/sh.py
1886 1887 1888 1889 1890 1891 1892 1893 |
|
shellfish.chmod(fspath: FsPath, mode: int) -> None
⚓︎
Change the access permissions of a file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file to chmod |
required |
mode
|
int
|
Permissions mode as an int |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
shellfish.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str]
⚓︎
Copy a file given a source-path and a destination-path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source fspath |
required |
dest
|
str
|
Destination fspath |
required |
dryrun
|
bool
|
Do not copy file if True just return the src and dest |
False
|
mkdirp
|
bool
|
Create parent directories if they do not exist |
False
|
Source code in libs/shellfish/shellfish/fs/__init__.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
shellfish.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None
⚓︎
Copy the directory/file src to the directory/file dest
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source directory/file to copy |
required |
dest
|
FsPath
|
Destination directory/file to copy |
required |
force
|
bool
|
Force the copy (like -f flag for cp in shell) |
True
|
recursive
|
bool
|
Recursive copy (like -r flag for cp in shell) |
False
|
r
|
bool
|
alias for recursive |
False
|
f
|
bool
|
alias for force |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If src is a directory and recursive and r are both |
Source code in libs/shellfish/shellfish/fs/__init__.py
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
|
shellfish.decode_stdio_bytes(stdio_bytes: Union[str, bytes], lf: bool = True) -> str
⚓︎
Return Stdio bytes from stdout/stderr as a string
Args:
stdio_bytes (bytes): STDOUT/STDERR bytes
lf (bool): Replace `
line endings with
`
Returns:
str: decoded stdio bytes
Source code in libs/shellfish/shellfish/sh.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
shellfish.dir_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
123 124 125 |
|
shellfish.dir_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.dirname(fspath: FsPath) -> str
⚓︎
Return dirname/parent-dir of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 |
|
shellfish.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all dirpaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
|
shellfish.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield directory-paths beneath a dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
shellfish.do(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[FsPath] = None, shell: bool = False, check: bool = False, tee: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
tee
|
bool
|
Flag to tee the subprocess stdout and stderr to sys.stdout/stderr |
False
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check against |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
if args and *popenargs are both given |
Source code in libs/shellfish/shellfish/sh.py
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
|
shellfish.do_async(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
If both *popenargs and args are given |
Source code in libs/shellfish/shellfish/sh.py
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
|
shellfish.doa(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Alias for sh.do_async
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 |
|
shellfish.exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
113 114 115 |
|
shellfish.export(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
if unable to parse key/val |
Source code in libs/shellfish/shellfish/sh.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 |
|
shellfish.extension(fspath: str, *, period: bool = False) -> str
⚓︎
Return the extension for a fspath
Examples:
>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/shellfish/fs/__init__.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
|
shellfish.file_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
118 119 120 |
|
shellfish.file_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]
⚓︎
Yield lines from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
File to yield lines from |
required |
keepends
|
bool
|
Flag to keep the ends of the file lines |
True
|
Yields:
Type | Description |
---|---|
Iterable[str]
|
Lines from the given fspath |
Examples:
>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
... file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
... file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
shellfish.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool
⚓︎
Compare 2 files for equality given their filepaths
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left
|
FsPath
|
Filepath 1 |
required |
right
|
FsPath
|
Filepath 2 |
required |
shallow
|
bool
|
Check only size and modification time if True |
True
|
blocksize
|
int
|
Chunk size to read files |
65536
|
Returns:
Type | Description |
---|---|
bool
|
True if files are equal, False otherwise |
Source code in libs/shellfish/shellfish/fs/__init__.py
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
shellfish.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
|
shellfish.filepath_mtimedelta_sec(filepath: FsPath) -> float
⚓︎
Return the seconds since the file(path) was last modified
Source code in libs/shellfish/shellfish/fs/__init__.py
378 379 380 |
|
shellfish.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]]
⚓︎
Return a files_gen() and a dirs_gen() in one swell-foop
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath is a directory |
True
|
Returns:
Type | Description |
---|---|
Tuple[Iterator[str], Iterator[str]]
|
A tuple of two generators (files_gen(), dirs_gen()) |
Examples:
>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2a']
>>> _files, _dirs = files_dirs_gen(tmpdir)
>>> _files = list(_files)
>>> _dirs = list(_dirs)
>>> files_n_dirs_list = list(sorted(set(_files + _dirs)))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
shellfish.files_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield file-paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields file-paths (absolute or relative) |
Examples:
>>> tmpdir = 'files_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt',
'files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt']
>>> files_list = list(sorted(set(files_gen(tmpdir))))
>>> files_list = [el.replace('\\', '/') for el in files_list]
>>> pprint(files_list)
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> pprint(list(sorted(set(expected_files))))
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> list(sorted(set(files_list))) == list(sorted(set(expected_files)))
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
shellfish.filesize(fspath: FsPath) -> int
⚓︎
Return the size of the given file(path) in bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath as a string or pathlib.Path object |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
size of the fspath in bytes |
Source code in libs/shellfish/shellfish/fs/__init__.py
163 164 165 166 167 168 169 170 171 172 173 |
|
shellfish.filesize_async(fspath: FsPath) -> int
async
⚓︎
Return the size of the file at the given fspath
Examples:
>>> from asyncio import run as aiorun
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmpdir:
... tmpdir = Path(tmpdir)
... fpath = tmpdir / "test.txt"
... written = fpath.write_text("hello world")
... aiorun(filesize_async(fpath))
11
Source code in libs/shellfish/shellfish/fs/_async.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
shellfish.flatten_args(*args: Union[Any, List[Any]]) -> List[str]
⚓︎
Flatten possibly nested iterables of sequences to a list of strings
Examples:
>>> list(flatten_args("cmd", ["uno", "dos", "tres"]))
['cmd', 'uno', 'dos', 'tres']
>>> list(flatten_args("cmd", ["uno", "dos", "tres", ["4444", "five"]]))
['cmd', 'uno', 'dos', 'tres', '4444', 'five']
Source code in libs/shellfish/shellfish/sh.py
834 835 836 837 838 839 840 841 842 843 844 |
|
shellfish.fspath(fspath: FsPath) -> str
⚓︎
Alias for os._fspath; returns fspath string for any type of path
Source code in libs/shellfish/shellfish/fs/__init__.py
93 94 95 |
|
shellfish.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish.is_dir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.is_file(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
133 134 135 |
|
shellfish.is_file_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.is_link(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; alias for islink
Source code in libs/shellfish/shellfish/fs/__init__.py
138 139 140 |
|
shellfish.is_link_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.isdir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
103 104 105 |
|
shellfish.isdir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.isfile(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
98 99 100 |
|
shellfish.isfile_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.islink(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
108 109 110 |
|
shellfish.islink_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.listdir_async(fspath: FsPath) -> List[str]
async
⚓︎
Async version of os.listdir
Source code in libs/shellfish/shellfish/fs/_async.py
133 134 135 |
|
shellfish.listdir_gen(fspath: FsPath = '.', *, abspath: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = False, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[Path]
⚓︎
Return an iterator of strings from DirEntries
Examples >>> tmpdir = 'listdir_gen.doctest' >>> from shellfish import sh >>> from os import makedirs, path, chdir >>> from shutil import rmtree >>> _makedirs(tmpdir, exist_ok=True) >>> pwd = sh.pwd() >>> sh.cd(tmpdir) >>> filepath_parts = [ ... ("dir", "file1.txt"), ... ("dir", "file2.txt"), ... ("dir", "file3.txt"), ... ("dir", "data1.json"), ... ("dir", "dir2", "file1.txt"), ... ("dir", "dir2", "file2.txt"), ... ("dir", "dir2", "file3.txt"), ... ("dir", "dir2a", "file1.txt"), ... ("dir", "dir2a", "file2.txt"), ... ("dir", "dir2a", "file3.txt"), ... ] >>> from shellfish.fs import touch >>> expected_files = [] >>> for f in filepath_parts: ... fspath = path.join(*f) ... fspath = path.join(tmpdir, fspath) ... dirpath = path.dirname(fspath) ... expected_files.append(fspath) ... _makedirs(dirpath, exist_ok=True) ... touch(fspath) >>> dirpath = path.join(tmpdir, 'dir') >>> dirpath.replace("\", "/") 'listdir_gen.doctest/dir' >>> sorted(listdir_gen(dirpath, dirs=False, symlinks=False)) ['data1.json', 'file1.txt', 'file2.txt', 'file3.txt'] >>> abspaths = sorted(listdir_gen(dirpath, abspath=True, dirs=False, symlinks=False)) >>> for abspath in [p.replace("\", "/") for p in abspaths]: ... print(abspath) listdir_gen.doctest/dir/data1.json listdir_gen.doctest/dir/file1.txt listdir_gen.doctest/dir/file2.txt listdir_gen.doctest/dir/file3.txt >>> sh.cd(pwd) >>> import os >>> if path.exists(tmpdir): ... rmtree(tmpdir) >>> path.isdir(tmpdir) False
Source code in libs/shellfish/shellfish/fs/__init__.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
shellfish.ls(dirpath: FsPath = '.', abspath: bool = False) -> List[str]
⚓︎
List files and dirs given a dirpath (defaults to pwd)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
path-string to directory to list |
'.'
|
abspath
|
bool
|
Give absolute paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of the directory items |
Source code in libs/shellfish/shellfish/sh.py
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 |
|
shellfish.ls_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the directories in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want list directories |
'.'
|
abspath
|
bool
|
Return absolute directory paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of directories as strings |
Source code in libs/shellfish/shellfish/sh.py
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 |
|
shellfish.ls_files(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the files in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want to list files |
'.'
|
abspath
|
bool
|
Return absolute filepaths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of files as strings |
Source code in libs/shellfish/shellfish/sh.py
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 |
|
shellfish.ls_files_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> Tuple[List[str], List[str]]
⚓︎
List the files and directories given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to execute on |
'.'
|
abspath
|
bool
|
Return absolute file/directory paths |
False
|
Returns:
Type | Description |
---|---|
Tuple[List[str], List[str]]
|
Two lists of strings; the first is a list of the files and the second is a list of the directories |
Source code in libs/shellfish/shellfish/sh.py
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 |
|
shellfish.lstat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.mkdir(fspath: FsPath, *, parents: bool = False, p: bool = False, exist_ok: bool = False) -> None
⚓︎
Make directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to create |
required |
parents
|
bool
|
Make parent dirs if True; do not make parent dirs if False |
False
|
p
|
bool
|
Make parent dirs if True; do not make parent dirs if False (alias of parents) |
False
|
exist_ok
|
bool
|
Throw error if directory exists and exist_ok is False |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
|
shellfish.mkdirp(fspath: FsPath) -> None
⚓︎
Make directory and parents
Source code in libs/shellfish/shellfish/fs/__init__.py
1435 1436 1437 |
|
shellfish.move(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 |
|
shellfish.mv(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/sh.py
2211 2212 2213 2214 2215 2216 2217 2218 2219 |
|
shellfish.path_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 |
|
shellfish.pwd() -> str
⚓︎
Return present-working-directory path string; alias for os.getcwd
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
present working directory as string |
Examples:
>>> import os
>>> pwd() == os.getcwd()
True
Source code in libs/shellfish/shellfish/sh.py
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 |
|
shellfish.q(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> q("hello world")
"'hello world'"
>>> q("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 |
|
shellfish.quote(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> quote("hello world")
"'hello world'"
>>> quote("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 |
|
shellfish.rbytes(filepath: FsPath) -> bytes
⚓︎
Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "rbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> wbytes(fspath, bites_to_save)
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
shellfish.rbytes_async(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> Iterable[bytes]
⚓︎
Yield bytes from a given fspath
Source code in libs/shellfish/shellfish/fs/__init__.py
1061 1062 1063 1064 1065 1066 1067 1068 |
|
shellfish.rbytes_gen_async(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.rjson(filepath: FsPath) -> Any
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
|
shellfish.rjson_async(filepath: FsPath) -> Any
async
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
shellfish.rm(fspath: FsPath, *, force: bool = False, recursive: bool = False, verbose: bool = False, f: bool = False, r: bool = False, v: bool = False, dryrun: bool = False) -> None
⚓︎
Remove files & directories in the style of the shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory to remove |
required |
force
|
bool
|
Flag to force removal; ignore missing |
False
|
recursive
|
bool
|
Flag to remove recursively (like the |
False
|
verbose
|
bool
|
Flag to be verbose |
False
|
f
|
bool
|
alias for force kwarg |
False
|
v
|
bool
|
alias for verbose |
False
|
r
|
bool
|
alias for recursive kwarg |
False
|
dryrun
|
bool
|
Flag to not actually remove anything |
False
|
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/sh.py
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 |
|
shellfish.rm_gen(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False) -> Generator[str, Any, Any]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): Force removal of files and directories
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
shellfish.rmdir(fspath: FsPath, *, force: bool = False, recursive: bool = False) -> None
⚓︎
Remove directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to remove |
required |
force
|
bool
|
Force removal of files and directories |
False
|
recursive
|
bool
|
Recursively remove all contents if True |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
shellfish.rmfile(fspath: FsPath, *, dryrun: bool = False) -> str
⚓︎
Remove a file at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath to remove |
required |
dryrun
|
bool
|
Do not remove file if True |
False
|
Returns:
Type | Description |
---|---|
str
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
|
shellfish.rstring(filepath: FsPath, *, encoding: str = 'utf-8') -> str
⚓︎
Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
Encoding to use for reading the file |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "lstring.doctest.txt"
>>> sstring(fspath, r'Check out this string')
21
>>> lstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
|
shellfish.rstring_async(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.safepath(fspath: FsPath) -> str
⚓︎
Check if a file/dir path is save/unused; returns an unused path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
file-system path; file or directory path string or Path obj |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
file/dir path that does not exist and contains the given path |
Source code in libs/shellfish/shellfish/fs/__init__.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
shellfish.scandir(dirpath: FsPath = '.') -> Iterable[DirEntry[AnyStr]]
⚓︎
Typed version of os.scandir
Source code in libs/shellfish/shellfish/fs/__init__.py
176 177 178 179 180 |
|
shellfish.scandir_gen(fspath: FsPath = '.', *, recursive: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = True, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[DirEntry[str]]
⚓︎
Return an iterator of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
(FsPath): dirpath to look through |
'.'
|
recursive
|
bool
|
recursively scan the directory |
False
|
follow_symlinks
|
bool
|
follow symlinks when checking for dirs and files |
True
|
files
|
bool
|
include files |
True
|
dirs
|
bool
|
include directories |
True
|
symlinks
|
bool
|
include symlinks |
True
|
dirs_only
|
bool
|
only include directories |
False
|
files_only
|
bool
|
only include files |
False
|
symlinks_only
|
bool
|
only include symlinks |
False
|
Returns:
Type | Description |
---|---|
Iterator[DirEntry[str]]
|
Iterator[DirEntry]: Iterator of os.DirEntry objects |
Raises:
Type | Description |
---|---|
ValueError
|
if any of the kwargs ( |
Source code in libs/shellfish/shellfish/fs/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.scandir_list(dirpath: FsPath = '.') -> List[DirEntry[AnyStr]]
⚓︎
Return a list of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Dirpath to scan |
'.'
|
Returns:
Type | Description |
---|---|
List[DirEntry[AnyStr]]
|
List[DirEntry]: List of os.DirEntry objects |
Source code in libs/shellfish/shellfish/fs/__init__.py
183 184 185 186 187 188 189 190 191 192 193 |
|
shellfish.seconds2hrtime(seconds: Union[float, int]) -> Tuple[int, int]
⚓︎
Return hr-time Tuple[int, int] (seconds, nanoseconds)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
Tuple[int, int]
|
Tuple[int, int]: (seconds, nanoseconds) |
Source code in libs/shellfish/shellfish/sh.py
383 384 385 386 387 388 389 390 391 392 393 394 |
|
shellfish.sep_join(path_strings: Iterator[str]) -> str
⚓︎
Join iterable of strings on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1319 1320 1321 |
|
shellfish.sep_lstrip(fspath: FsPath) -> str
⚓︎
Left-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1329 1330 1331 |
|
shellfish.sep_rstrip(fspath: FsPath) -> str
⚓︎
Right-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1334 1335 1336 |
|
shellfish.sep_split(fspath: FsPath) -> Tuple[str, ...]
⚓︎
Split a string on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1314 1315 1316 |
|
shellfish.sep_strip(fspath: FsPath) -> str
⚓︎
Strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1324 1325 1326 |
|
shellfish.setenv(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Returns:
Type | Description |
---|---|
Tuple[str, str]
|
Tuple[str, str]: environment variable key/value pair |
Source code in libs/shellfish/shellfish/sh.py
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 |
|
shellfish.shebang(fspath: FsPath) -> Union[None, str]
⚓︎
Get the shebang string given a fspath; Returns None if no shebang
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file that might have a shebang |
required |
Returns:
Type | Description |
---|---|
Union[None, str]
|
Optional[str]: The shebang string if it exists, None otherwise |
Examples:
>>> from inspect import getabsfile
>>> script = 'ashellscript.sh'
>>> with open(script, 'w') as f:
... f.write('#!/bin/bash\necho "howdy"\n')
25
>>> shebang(script)
'#!/bin/bash'
>>> from os import remove
>>> remove(script)
Source code in libs/shellfish/shellfish/fs/__init__.py
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
|
shellfish.shell(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, shell: bool = True, extenv: bool = True, cwd: Optional[FsPath] = None, check: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously in current shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell; default is True for |
True
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check if ok |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 |
|
shellfish.shplit(string: str, comments: bool = False, posix: bool = True) -> List[str]
⚓︎
Typed alias for shlex.split
Source code in libs/shellfish/shellfish/sh.py
1932 1933 1934 |
|
shellfish.source(filepath: FsPath, _globals: bool = True) -> None
⚓︎
Execute/run a python file given a fspath and put globals in globasl
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Path to python file |
required |
_globals
|
bool
|
Exec using globals |
True
|
Source code in libs/shellfish/shellfish/sh.py
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 |
|
shellfish.stat(fspath: FsPath) -> os_stat_result
⚓︎
Return the os.stat_result object for a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory |
required |
Returns:
Type | Description |
---|---|
stat_result
|
os.stat_result: stat_result object |
Source code in libs/shellfish/shellfish/fs/__init__.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 |
|
shellfish.stat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.touch(fspath: FsPath, *, mkdirp: bool = True) -> None
⚓︎
Create an empty file given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path for where to make an empty file |
required |
mkdirp
|
bool
|
Make parent directories if they don't exist |
True
|
Source code in libs/shellfish/shellfish/fs/__init__.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
shellfish.tree(dirpath: FsPath, filterfn: Optional[Callable[[str], bool]] = None) -> str
⚓︎
Create a directory tree string given a directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory string to make tree for |
required |
filterfn
|
Optional[Callable[[str], bool]]
|
Function to filter sub-directories and sub-files with |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Directory-tree string |
Examples:
>>> tmpdir = 'tree.doctest'
>>> from os import makedirs; makedirs(tmpdir, exist_ok=True)
>>> from pathlib import Path
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... makedirs(dirpath, exist_ok=True)
... Path(fspath).touch()
>>> print(tree(tmpdir))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── file1.txt
├── file2.txt
└── file3.txt
>>> print(tree(tmpdir, lambda s: _DirTree._default_filter(s) and not "file2" in s))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ └── file3.txt
├── file1.txt
└── file3.txt
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/sh.py
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 |
|
shellfish.walk_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield all paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'walk_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f).replace('\\', '/')
... fspath = path.join(tmpdir, fspath).replace('\\', '/')
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = [el.replace('\\', '/') for el in sorted(set(expected_dirs))]
>>> from pprint import pprint
>>> pprint(expected_files)
['walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt']
>>> pprint(expected_dirs)
['walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2a']
>>> walk_gen_list = list(sorted(walk_gen(tmpdir)))
>>> walk_gen_list = [el.replace('\\', '/') for el in walk_gen_list]
>>> pprint(walk_gen_list)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> pprint(expected)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> walk_gen_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
shellfish.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> wbytes(fspath, bites_to_save)
20
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 |
|
shellfish.wbytes_async(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.wbytes_gen(filepath: FsPath, bytes_gen: Iterable[bytes], append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Iterable[bytes]
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes_gen.doctest.txt"
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save # they are bytes!
(b'These are some bytes... ', b'more bytes!')
>>> wbytes_gen(fspath, (b for b in bites_to_save))
35
>>> rbytes(fspath)
b'These are some bytes... more bytes!'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
shellfish.wbytes_gen_async(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.where(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
; alias of shellfish.sh.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 |
|
shellfish.which(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 |
|
shellfish.which_lru(cmd: str, path: Optional[str] = None) -> Optional[str]
cached
⚓︎
Return the result of shutil.which
and cache the results
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 |
|
shellfish.wjson(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, chmod: Optional[int] = None, append: bool = False, **kwargs: Any) -> int
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Append a newline to the end of the file |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
append
|
bool
|
Append to the file if True, overwrite otherwise; default |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dumpb |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 |
|
shellfish.wjson_async(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, append: bool = False, chmod: Optional[int] = None, **kwargs: Any) -> int
async
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dump |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "wjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "wjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
shellfish.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
String encoding to write file with |
'utf-8'
|
append
|
bool
|
Flag to append to file; default = False |
False
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "sstring.doctest.txt"
>>> wstring(fspath, r'Check out this string')
21
>>> rstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
shellfish.wstring_async(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
Modules⚓︎
shellfish.__about__
⚓︎
Package metadata/info
shellfish.__main__
⚓︎
pkg entry ~ python -m shellfish
Functions⚓︎
shellfish.__main__.main() -> None
⚓︎
Print package metadata
Source code in libs/shellfish/shellfish/__main__.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
shellfish.aios
⚓︎
aios = asyncio + os
Classes⚓︎
shellfish.aios.DirEntryAsync(dir_entry: os.DirEntry[AnyStr])
⚓︎
Bases: Generic[AnyStr]
DirEntryAsync os.DirEntry + async
Signature of os.DirEntry:
@final
class DirEntry(Generic[AnyStr]):
# This is what the scandir iterator yields
# The constructor is hidden
@property
def name(self) -> AnyStr: ...
@property
def path(self) -> AnyStr: ...
def inode(self) -> int: ...
def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...
def is_file(self, *, follow_symlinks: bool = True) -> bool: ...
def is_symlink(self) -> bool: ...
def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...
def __fspath__(self) -> AnyStr: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
Source code in libs/shellfish/shellfish/aios/__init__.py
80 81 |
|
Functions⚓︎
shellfish.aios.scandir(path: AnyStr) -> AsyncIterator[DirEntryAsync[AnyStr]]
async
⚓︎
Async version of os.scandir
Signature of os.scandir:
def scandir(path: AnyStr) -> Iterator[DirEntry[AnyStr]]: ...
Source code in libs/shellfish/shellfish/aios/__init__.py
110 111 112 113 114 115 116 117 118 119 120 121 |
|
shellfish.batman
⚓︎
batman = bat/cmd windows utils
Functions⚓︎
shellfish.batman.MKLINK(link: FsPath, target: FsPath, *, D: bool = False, H: bool = False, J: bool = False, check: bool = False) -> CompletedProcess[str]
⚓︎
Creates a symbolic link.
Returns:
Type | Description |
---|---|
CompletedProcess[str]
|
pass |
Output of MKLINK /?
:
MKLINK [[/D] | [/H] | [/J]] Link Target
/D Creates a directory symbolic link. Default is a file
symbolic link.
/H Creates a hard link instead of a symbolic link.
/J Creates a Directory Junction.
Link Specifies the new symbolic link name.
Target Specifies the path (relative or absolute) that the new link
refers to.
Source code in libs/shellfish/shellfish/batman.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
|
shellfish.batman.MKLINK_OPT(D: bool = False, H: bool = False, J: bool = False) -> Union[str, None]
⚓︎
Return the appropriate /D, /H, or /J option for windows mklink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
D
|
bool
|
|
False
|
H
|
bool
|
|
False
|
J
|
bool
|
|
False
|
Returns:
Type | Description |
---|---|
Union[str, None]
|
Union[str, None]: The appropriate /D, /H, or /J option for windows mklink |
Examples:
>>> MKLINK_OPT(D=True)
'/D'
>>> MKLINK_OPT(H=True)
'/H'
>>> MKLINK_OPT(J=True)
'/J'
>>> MKLINK_OPT()
>>> MKLINK_OPT(D=True, H=True)
Traceback (most recent call last):
...
ValueError: Only one of D, H, J can be True. Got True, True, False
Source code in libs/shellfish/shellfish/batman.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
shellfish.batman.RD(fspath: FsPath, *, S: bool = False, Q: bool = False, R: bool = False, P: bool = False, F: bool = False, X: bool = False, Y: bool = False, Z: bool = False, A: bool = False, check: bool = False) -> CompletedProcess[str]
⚓︎
Removes a directory.
Returns:
Type | Description |
---|---|
CompletedProcess[str]
|
pass |
Output of RD /?
:
RD [/S] [/Q] [/R] [/P] [/F] [/X] [/Y] [/Z] [/A] [Drive:]Path
/S Recursively removes subdirectories and files.
/Q Quiet. Do not display progress messages.
/R Recursively removes subdirectories and files.
/P Prompts before each removal.
/F Do not display confirmation messages.
/X Do not display confirmation messages.
/Y Do not display confirmation messages.
/Z Do not display confirmation messages.
/A Do not display confirmation messages.
Drive: Specifies the drive or root directory of the path.
Path Specifies the path to be removed.
Source code in libs/shellfish/shellfish/batman.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
shellfish.batman.bat(fspath: FsPath, *, check: bool = False, text: bool = True, shell: bool = False) -> CompletedProcess[AnyStr]
⚓︎
Run a bat file
Source code in libs/shellfish/shellfish/batman.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
shellfish.const
⚓︎
Constants
shellfish.dev
⚓︎
UNDER CONSTRUCTION
Modules⚓︎
shellfish.dev.do
⚓︎
shellfish.dev.do.Do(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
PRun => 'ProcessRun' for finished processes
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
shellfish.dev.do.Do.__property_fields__: Set[str]
property
⚓︎Returns a set of property names for the class that have a setter
shellfish.dev.do.Do.__contains__(key: _KT) -> bool
⚓︎Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.dev.do.Do.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.dev.do.Do.__getattr__(item: _KT) -> Any
⚓︎Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.dev.do.Do.__post_init__() -> Any
⚓︎Function place holder that is called after object initialization
Source code in libs/jsonbourne/jsonbourne/pydantic.py
98 99 |
|
shellfish.dev.do.Do.__setitem__(key: _KT, value: _VT) -> None
⚓︎Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.dev.do.Do.asdict() -> Dict[_KT, Any]
⚓︎Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.dev.do.Do.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.dev.do.Do.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.dev.do.Do.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.dev.do.Do.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.dev.do.Do.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.dev.do.Do.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.dev.do.Do.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.dev.do.Do.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.dev.do.Do.eject() -> Dict[_KT, _VT]
⚓︎Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.dev.do.Do.entries() -> ItemsView[_KT, _VT]
⚓︎Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.dev.do.Do.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.dev.do.Do.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.dev.do.Do.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.dev.do.Do.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.dev.do.Do.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.dev.do.Do.has_required_fields() -> bool
classmethod
⚓︎Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.dev.do.Do.is_default() -> bool
⚓︎Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.dev.do.Do.items() -> ItemsView[_KT, _VT]
⚓︎Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.dev.do.Do.json(*args: Any, **kwargs: Any) -> str
⚓︎Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.dev.do.Do.keys() -> KeysView[_KT]
⚓︎Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.dev.do.Do.recurse() -> None
⚓︎Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.dev.do.Do.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.dev.do.Do.to_dict() -> Dict[str, Any]
⚓︎Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.dev.do.Do.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.dev.do.Do.to_dict_filter_none() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.dev.do.Do.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.dev.do.Do.to_json_dict() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.dev.do.Do.to_json_obj() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.dev.do.Do.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.dev.do.Do.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.dev.do.Do.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.dev.do.DoDict
⚓︎
Bases: TypedDict
Do dictionary
shellfish.dev.popen_gen
⚓︎
shellfish.dev.popen_gen.popen_gen(*popenargs: Any, **popenkwargs: Any) -> Iterable[Tuple[Stdio, str]]
⚓︎Create and open a subprocess and yield tuples with stdout/stderr lines
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
Any
|
Args to be passed to Popen |
()
|
**popenkwargs
|
Any
|
Kwargs to be passed to Popen |
{}
|
Yields:
Type | Description |
---|---|
Iterable[Tuple[Stdio, str]]
|
Tuple[str, str]: Tuples that are of the form ('stdout', stdout_line) or ('stderr', stderr_line) for the stdout and stderr lines for the subprocess created. |
Source code in libs/shellfish/shellfish/dev/popen_gen.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
|
shellfish.dev.popen_gen.popen_pipes_gen(proc: Popen[AnyStr], timeout: Optional[float] = None) -> Iterable[Tuple[Stdio, str]]
⚓︎Yield stdout and stderr lines from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
Popen
|
Popen process |
required |
timeout
|
Optional[float]
|
Timeout in seconds. Defaults to None. |
None
|
Yields:
Type | Description |
---|---|
Iterable[Tuple[Stdio, str]]
|
Tuple[Stdio, str]: Tuples with stdio enum marker followed by a string |
Raises:
Type | Description |
---|---|
ValueError
|
if proc is not Popen or proc.stdout or proc.stderr is None |
Source code in libs/shellfish/shellfish/dev/popen_gen.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
|
shellfish.dotenv
⚓︎
dot.env utils
Functions⚓︎
shellfish.dotenv.ldotenv(fspath: Optional[FsPath] = None) -> Dict[str, str]
⚓︎
Load a dotenv file from a fspath and return the keyvalues as a dict
Examples:
>>> import os
>>> import shutil
>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> with open('.env.test', 'w') as f: f.write('\n'.join(dot_env_list))
13
>>> ldotenv('.env.test')
{'a': '1', 'ANOTHER': '2'}
>>> if os.path.exists('.env.test'): os.remove('.env.test')
>>> os.makedirs('env-test', exist_ok=True)
>>> with open(os.path.join('env-test', '.env'), 'w') as f: f.write('\n'.join(dot_env_list))
13
>>> ldotenv('env-test')
{'a': '1', 'ANOTHER': '2'}
>>> if os.path.exists('env-test'): shutil.rmtree('env-test')
>>> ldotenv('path/does/not/exist')
Traceback (most recent call last):
...
ValueError: Given fspath/dirpath does not exist: path/does/not/exist
Source code in libs/shellfish/shellfish/dotenv.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
shellfish.dotenv.parse_dotenv(string: str) -> Dict[str, str]
⚓︎
Parse env string to dictionary
Examples:
>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> dotenv_string = '\n'.join(dot_env_list)
>>> parse_dotenv(dotenv_string)
{'a': '1', 'ANOTHER': '2'}
Source code in libs/shellfish/shellfish/dotenv.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
shellfish.dotenv.parse_env(string: str) -> Dict[str, str]
⚓︎
Parse env string to dictionary
Examples:
>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> dotenv_string = '\n'.join(dot_env_list)
>>> parse_dotenv(dotenv_string)
{'a': '1', 'ANOTHER': '2'}
Source code in libs/shellfish/shellfish/dotenv.py
88 89 90 91 92 93 94 95 96 97 98 |
|
shellfish.dotenv.strip_comments(string: str) -> str
⚓︎
Remove comments from python/shell scripts given the script as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string with |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
input string with comments striped out |
Examples:
Here is an example of stripping comments from a python-ish script:
>>> python_script_ish = r'''# some encoding
... # this is a comment
... # this is another comment
... print('hello bob')
... print('hello bobert') # bob is short for bobert
... '''
>>> a = strip_comments(python_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', "print('hello bob')", "print('hello bobert') "]
Here is an example of stripping comments from a bash/shell-ish script:
>>> bash_script_ish = r'''#!/bin/bash
... # this is a comment
... # this is another comment
... echo "hello"
... echo "hello again" # comment
... '''
>>> a = strip_comments(bash_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', 'echo "hello"', 'echo "hello again" ']
Source code in libs/shellfish/shellfish/dotenv.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
|
shellfish.echo
⚓︎
Echo/Print
Functions⚓︎
shellfish.echo.echo(*objects: Any, sep: str = ' ', end: str = '\n', file: Optional[IO[str]] = None, flush: bool = False) -> None
⚓︎
Print/echo function
Args:
*objects: Item(s) to print/echo
sep: Separator to print with
end: End of print suffix; defaults to `
` file: File like object to write to if not stdout flush: Flush the file after writing
Examples:
>>> echo("shellfish")
shellfish
Source code in libs/shellfish/shellfish/echo.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
shellfish.exe
⚓︎
Exes/commands
Classes⚓︎
shellfish.exe.ExeABC(cmd: str, subcmd: Optional[Union[Tuple[str, ...], List[str], str]] = None, abspath: Optional[str] = None, check: bool = False, cwd: Optional[FsPath] = None, env: Optional[Dict[str, str]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, shell: bool = False, timeout: Optional[Union[float, int]] = None, verbose: bool = False)
⚓︎
Source code in libs/shellfish/shellfish/exe.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
shellfish.exe.ExeABC.__post_init__() -> None
⚓︎Post-initialization
Source code in libs/shellfish/shellfish/exe.py
82 83 |
|
shellfish.exe.ExeABC.which() -> str
⚓︎Return the path to the exe
Source code in libs/shellfish/shellfish/exe.py
126 127 128 |
|
Functions⚓︎
Modules⚓︎
shellfish.fs
⚓︎
file-system utils
Classes⚓︎
shellfish.fs.Stdio
⚓︎
Bases: IntEnum
Standard-io enum object
Functions⚓︎
shellfish.fs.chmod(fspath: FsPath, mode: int) -> None
⚓︎
Change the access permissions of a file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file to chmod |
required |
mode
|
int
|
Permissions mode as an int |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
shellfish.fs.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str]
⚓︎
Copy a file given a source-path and a destination-path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source fspath |
required |
dest
|
str
|
Destination fspath |
required |
dryrun
|
bool
|
Do not copy file if True just return the src and dest |
False
|
mkdirp
|
bool
|
Create parent directories if they do not exist |
False
|
Source code in libs/shellfish/shellfish/fs/__init__.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
shellfish.fs.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None
⚓︎
Copy the directory/file src to the directory/file dest
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source directory/file to copy |
required |
dest
|
FsPath
|
Destination directory/file to copy |
required |
force
|
bool
|
Force the copy (like -f flag for cp in shell) |
True
|
recursive
|
bool
|
Recursive copy (like -r flag for cp in shell) |
False
|
r
|
bool
|
alias for recursive |
False
|
f
|
bool
|
alias for force |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If src is a directory and recursive and r are both |
Source code in libs/shellfish/shellfish/fs/__init__.py
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
|
shellfish.fs.dir_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
123 124 125 |
|
shellfish.fs.dir_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.fs.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all dirpaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
|
shellfish.fs.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield directory-paths beneath a dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
shellfish.fs.exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
113 114 115 |
|
shellfish.fs.extension(fspath: str, *, period: bool = False) -> str
⚓︎
Return the extension for a fspath
Examples:
>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/shellfish/fs/__init__.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
|
shellfish.fs.file_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
118 119 120 |
|
shellfish.fs.file_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.fs.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]
⚓︎
Yield lines from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
File to yield lines from |
required |
keepends
|
bool
|
Flag to keep the ends of the file lines |
True
|
Yields:
Type | Description |
---|---|
Iterable[str]
|
Lines from the given fspath |
Examples:
>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
... file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
... file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
shellfish.fs.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool
⚓︎
Compare 2 files for equality given their filepaths
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left
|
FsPath
|
Filepath 1 |
required |
right
|
FsPath
|
Filepath 2 |
required |
shallow
|
bool
|
Check only size and modification time if True |
True
|
blocksize
|
int
|
Chunk size to read files |
65536
|
Returns:
Type | Description |
---|---|
bool
|
True if files are equal, False otherwise |
Source code in libs/shellfish/shellfish/fs/__init__.py
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
shellfish.fs.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
|
shellfish.fs.filepath_mtimedelta_sec(filepath: FsPath) -> float
⚓︎
Return the seconds since the file(path) was last modified
Source code in libs/shellfish/shellfish/fs/__init__.py
378 379 380 |
|
shellfish.fs.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]]
⚓︎
Return a files_gen() and a dirs_gen() in one swell-foop
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath is a directory |
True
|
Returns:
Type | Description |
---|---|
Tuple[Iterator[str], Iterator[str]]
|
A tuple of two generators (files_gen(), dirs_gen()) |
Examples:
>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2a']
>>> _files, _dirs = files_dirs_gen(tmpdir)
>>> _files = list(_files)
>>> _dirs = list(_dirs)
>>> files_n_dirs_list = list(sorted(set(_files + _dirs)))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
shellfish.fs.files_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield file-paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields file-paths (absolute or relative) |
Examples:
>>> tmpdir = 'files_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt',
'files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt']
>>> files_list = list(sorted(set(files_gen(tmpdir))))
>>> files_list = [el.replace('\\', '/') for el in files_list]
>>> pprint(files_list)
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> pprint(list(sorted(set(expected_files))))
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> list(sorted(set(files_list))) == list(sorted(set(expected_files)))
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
shellfish.fs.filesize(fspath: FsPath) -> int
⚓︎
Return the size of the given file(path) in bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath as a string or pathlib.Path object |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
size of the fspath in bytes |
Source code in libs/shellfish/shellfish/fs/__init__.py
163 164 165 166 167 168 169 170 171 172 173 |
|
shellfish.fs.filesize_async(fspath: FsPath) -> int
async
⚓︎
Return the size of the file at the given fspath
Examples:
>>> from asyncio import run as aiorun
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmpdir:
... tmpdir = Path(tmpdir)
... fpath = tmpdir / "test.txt"
... written = fpath.write_text("hello world")
... aiorun(filesize_async(fpath))
11
Source code in libs/shellfish/shellfish/fs/_async.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
shellfish.fs.fspath(fspath: FsPath) -> str
⚓︎
Alias for os._fspath; returns fspath string for any type of path
Source code in libs/shellfish/shellfish/fs/__init__.py
93 94 95 |
|
shellfish.fs.glob(pattern: str, *, recursive: bool = False, r: bool = False) -> Iterator[str]
⚓︎
Return an iterator of fspaths matching the given glob pattern
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
Glob pattern |
required |
recursive
|
bool
|
Recursively search directories if True |
False
|
r
|
bool
|
Recursively search directories if True (Alias for recursive) |
False
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Iterator[str]: Iterator of fspaths matching the glob pattern |
Source code in libs/shellfish/shellfish/fs/__init__.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
|
shellfish.fs.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish.fs.is_dir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.fs.is_file(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
133 134 135 |
|
shellfish.fs.is_file_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.fs.is_link(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; alias for islink
Source code in libs/shellfish/shellfish/fs/__init__.py
138 139 140 |
|
shellfish.fs.is_link_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.fs.isdir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
103 104 105 |
|
shellfish.fs.isdir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.fs.isfile(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
98 99 100 |
|
shellfish.fs.isfile_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.fs.islink(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
108 109 110 |
|
shellfish.fs.islink_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.fs.listdir_async(fspath: FsPath) -> List[str]
async
⚓︎
Async version of os.listdir
Source code in libs/shellfish/shellfish/fs/_async.py
133 134 135 |
|
shellfish.fs.listdir_gen(fspath: FsPath = '.', *, abspath: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = False, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[Path]
⚓︎
Return an iterator of strings from DirEntries
Examples >>> tmpdir = 'listdir_gen.doctest' >>> from shellfish import sh >>> from os import makedirs, path, chdir >>> from shutil import rmtree >>> _makedirs(tmpdir, exist_ok=True) >>> pwd = sh.pwd() >>> sh.cd(tmpdir) >>> filepath_parts = [ ... ("dir", "file1.txt"), ... ("dir", "file2.txt"), ... ("dir", "file3.txt"), ... ("dir", "data1.json"), ... ("dir", "dir2", "file1.txt"), ... ("dir", "dir2", "file2.txt"), ... ("dir", "dir2", "file3.txt"), ... ("dir", "dir2a", "file1.txt"), ... ("dir", "dir2a", "file2.txt"), ... ("dir", "dir2a", "file3.txt"), ... ] >>> from shellfish.fs import touch >>> expected_files = [] >>> for f in filepath_parts: ... fspath = path.join(*f) ... fspath = path.join(tmpdir, fspath) ... dirpath = path.dirname(fspath) ... expected_files.append(fspath) ... _makedirs(dirpath, exist_ok=True) ... touch(fspath) >>> dirpath = path.join(tmpdir, 'dir') >>> dirpath.replace("\", "/") 'listdir_gen.doctest/dir' >>> sorted(listdir_gen(dirpath, dirs=False, symlinks=False)) ['data1.json', 'file1.txt', 'file2.txt', 'file3.txt'] >>> abspaths = sorted(listdir_gen(dirpath, abspath=True, dirs=False, symlinks=False)) >>> for abspath in [p.replace("\", "/") for p in abspaths]: ... print(abspath) listdir_gen.doctest/dir/data1.json listdir_gen.doctest/dir/file1.txt listdir_gen.doctest/dir/file2.txt listdir_gen.doctest/dir/file3.txt >>> sh.cd(pwd) >>> import os >>> if path.exists(tmpdir): ... rmtree(tmpdir) >>> path.isdir(tmpdir) False
Source code in libs/shellfish/shellfish/fs/__init__.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
shellfish.fs.lstat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.fs.mkdir(fspath: FsPath, *, parents: bool = False, p: bool = False, exist_ok: bool = False) -> None
⚓︎
Make directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to create |
required |
parents
|
bool
|
Make parent dirs if True; do not make parent dirs if False |
False
|
p
|
bool
|
Make parent dirs if True; do not make parent dirs if False (alias of parents) |
False
|
exist_ok
|
bool
|
Throw error if directory exists and exist_ok is False |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
|
shellfish.fs.mkdirp(fspath: FsPath) -> None
⚓︎
Make directory and parents
Source code in libs/shellfish/shellfish/fs/__init__.py
1435 1436 1437 |
|
shellfish.fs.move(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 |
|
shellfish.fs.path_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 |
|
shellfish.fs.rbytes(filepath: FsPath) -> bytes
⚓︎
Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "rbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> wbytes(fspath, bites_to_save)
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
shellfish.fs.rbytes_async(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.fs.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> Iterable[bytes]
⚓︎
Yield bytes from a given fspath
Source code in libs/shellfish/shellfish/fs/__init__.py
1061 1062 1063 1064 1065 1066 1067 1068 |
|
shellfish.fs.rbytes_gen_async(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.fs.rjson(filepath: FsPath) -> Any
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
|
shellfish.fs.rjson_async(filepath: FsPath) -> Any
async
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
shellfish.fs.rm(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False, verbose: bool = False) -> Union[List[str], None]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): ignore errors and missing files/dirs; default is False
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 |
|
shellfish.fs.rm_gen(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False) -> Generator[str, Any, Any]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): Force removal of files and directories
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
shellfish.fs.rmdir(fspath: FsPath, *, force: bool = False, recursive: bool = False) -> None
⚓︎
Remove directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to remove |
required |
force
|
bool
|
Force removal of files and directories |
False
|
recursive
|
bool
|
Recursively remove all contents if True |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
shellfish.fs.rmfile(fspath: FsPath, *, dryrun: bool = False) -> str
⚓︎
Remove a file at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath to remove |
required |
dryrun
|
bool
|
Do not remove file if True |
False
|
Returns:
Type | Description |
---|---|
str
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
|
shellfish.fs.rstring(filepath: FsPath, *, encoding: str = 'utf-8') -> str
⚓︎
Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
Encoding to use for reading the file |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "lstring.doctest.txt"
>>> sstring(fspath, r'Check out this string')
21
>>> lstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
|
shellfish.fs.rstring_async(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.fs.safepath(fspath: FsPath) -> str
⚓︎
Check if a file/dir path is save/unused; returns an unused path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
file-system path; file or directory path string or Path obj |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
file/dir path that does not exist and contains the given path |
Source code in libs/shellfish/shellfish/fs/__init__.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
shellfish.fs.scandir(dirpath: FsPath = '.') -> Iterable[DirEntry[AnyStr]]
⚓︎
Typed version of os.scandir
Source code in libs/shellfish/shellfish/fs/__init__.py
176 177 178 179 180 |
|
shellfish.fs.scandir_gen(fspath: FsPath = '.', *, recursive: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = True, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[DirEntry[str]]
⚓︎
Return an iterator of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
(FsPath): dirpath to look through |
'.'
|
recursive
|
bool
|
recursively scan the directory |
False
|
follow_symlinks
|
bool
|
follow symlinks when checking for dirs and files |
True
|
files
|
bool
|
include files |
True
|
dirs
|
bool
|
include directories |
True
|
symlinks
|
bool
|
include symlinks |
True
|
dirs_only
|
bool
|
only include directories |
False
|
files_only
|
bool
|
only include files |
False
|
symlinks_only
|
bool
|
only include symlinks |
False
|
Returns:
Type | Description |
---|---|
Iterator[DirEntry[str]]
|
Iterator[DirEntry]: Iterator of os.DirEntry objects |
Raises:
Type | Description |
---|---|
ValueError
|
if any of the kwargs ( |
Source code in libs/shellfish/shellfish/fs/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.fs.scandir_list(dirpath: FsPath = '.') -> List[DirEntry[AnyStr]]
⚓︎
Return a list of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Dirpath to scan |
'.'
|
Returns:
Type | Description |
---|---|
List[DirEntry[AnyStr]]
|
List[DirEntry]: List of os.DirEntry objects |
Source code in libs/shellfish/shellfish/fs/__init__.py
183 184 185 186 187 188 189 190 191 192 193 |
|
shellfish.fs.sep_join(path_strings: Iterator[str]) -> str
⚓︎
Join iterable of strings on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1319 1320 1321 |
|
shellfish.fs.sep_lstrip(fspath: FsPath) -> str
⚓︎
Left-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1329 1330 1331 |
|
shellfish.fs.sep_rstrip(fspath: FsPath) -> str
⚓︎
Right-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1334 1335 1336 |
|
shellfish.fs.sep_split(fspath: FsPath) -> Tuple[str, ...]
⚓︎
Split a string on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1314 1315 1316 |
|
shellfish.fs.sep_strip(fspath: FsPath) -> str
⚓︎
Strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1324 1325 1326 |
|
shellfish.fs.shebang(fspath: FsPath) -> Union[None, str]
⚓︎
Get the shebang string given a fspath; Returns None if no shebang
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file that might have a shebang |
required |
Returns:
Type | Description |
---|---|
Union[None, str]
|
Optional[str]: The shebang string if it exists, None otherwise |
Examples:
>>> from inspect import getabsfile
>>> script = 'ashellscript.sh'
>>> with open(script, 'w') as f:
... f.write('#!/bin/bash\necho "howdy"\n')
25
>>> shebang(script)
'#!/bin/bash'
>>> from os import remove
>>> remove(script)
Source code in libs/shellfish/shellfish/fs/__init__.py
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
|
shellfish.fs.stat(fspath: FsPath) -> os_stat_result
⚓︎
Return the os.stat_result object for a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory |
required |
Returns:
Type | Description |
---|---|
stat_result
|
os.stat_result: stat_result object |
Source code in libs/shellfish/shellfish/fs/__init__.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 |
|
shellfish.fs.stat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.fs.touch(fspath: FsPath, *, mkdirp: bool = True) -> None
⚓︎
Create an empty file given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path for where to make an empty file |
required |
mkdirp
|
bool
|
Make parent directories if they don't exist |
True
|
Source code in libs/shellfish/shellfish/fs/__init__.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
shellfish.fs.walk_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield all paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'walk_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f).replace('\\', '/')
... fspath = path.join(tmpdir, fspath).replace('\\', '/')
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = [el.replace('\\', '/') for el in sorted(set(expected_dirs))]
>>> from pprint import pprint
>>> pprint(expected_files)
['walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt']
>>> pprint(expected_dirs)
['walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2a']
>>> walk_gen_list = list(sorted(walk_gen(tmpdir)))
>>> walk_gen_list = [el.replace('\\', '/') for el in walk_gen_list]
>>> pprint(walk_gen_list)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> pprint(expected)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> walk_gen_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
shellfish.fs.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> wbytes(fspath, bites_to_save)
20
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 |
|
shellfish.fs.wbytes_async(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.fs.wbytes_gen(filepath: FsPath, bytes_gen: Iterable[bytes], append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Iterable[bytes]
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes_gen.doctest.txt"
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save # they are bytes!
(b'These are some bytes... ', b'more bytes!')
>>> wbytes_gen(fspath, (b for b in bites_to_save))
35
>>> rbytes(fspath)
b'These are some bytes... more bytes!'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
shellfish.fs.wbytes_gen_async(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.fs.wjson(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, chmod: Optional[int] = None, append: bool = False, **kwargs: Any) -> int
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Append a newline to the end of the file |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
append
|
bool
|
Append to the file if True, overwrite otherwise; default |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dumpb |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 |
|
shellfish.fs.wjson_async(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, append: bool = False, chmod: Optional[int] = None, **kwargs: Any) -> int
async
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dump |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "wjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "wjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
shellfish.fs.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
String encoding to write file with |
'utf-8'
|
append
|
bool
|
Flag to append to file; default = False |
False
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "sstring.doctest.txt"
>>> wstring(fspath, r'Check out this string')
21
>>> rstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
shellfish.fs.wstring_async(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
Modules⚓︎
shellfish.fs.promises
⚓︎
shellfish.fs.promises
shellfish.fs.promises.dir_exists(fspath: FsPath) -> bool
async
⚓︎Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.fs.promises.file_exists(fspath: FsPath) -> bool
async
⚓︎Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.fs.promises.is_dir(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.fs.promises.is_file(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.fs.promises.is_link(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.fs.promises.isdir(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.fs.promises.isfile(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.fs.promises.islink(fspath: FsPath) -> bool
async
⚓︎Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.fs.promises.lstat(fspath: FsPath) -> os.stat_result
async
⚓︎Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.fs.promises.rbytes(filepath: FsPath) -> bytes
async
⚓︎(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.fs.promises.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.fs.promises.rstring(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.fs.promises.stat(fspath: FsPath) -> os.stat_result
async
⚓︎Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.fs.promises.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.fs.promises.wbytes_gen(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.fs.promises.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
shellfish.libhash
⚓︎
Classes⚓︎
shellfish.libhash.Hashed(b: bytes, s: str)
dataclass
⚓︎
Hashed Result
Functions⚓︎
shellfish.libhash.hash_bytes_gen(it: Iterator[bytes], hashlike: HashLike) -> str
⚓︎
Return the hash of an iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
it
|
Iterator[bytes]
|
Iterator of bytes |
required |
hashlike
|
hash
|
Hash like object; can be a string or a '_Hash' object |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Hash of the iterator |
Source code in libs/shellfish/shellfish/libhash.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
shellfish.libhash.hasher(obj: HashLike) -> '_Hash'
⚓︎
Return a hash object from a string or a hash object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Union[str, hash]
|
String or hash object |
required |
Returns:
Name | Type | Description |
---|---|---|
hash |
'_Hash'
|
Hash object |
Examples:
>>> hashobj = hasher("sha256")
>>> hashobj.update(b"Hello World")
>>> hashobj.hexdigest()
'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
Source code in libs/shellfish/shellfish/libhash.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
shellfish.libhash.string2hasher(string: str) -> '_Hash'
⚓︎
Return a hash object from a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
String to hash |
required |
Returns:
Name | Type | Description |
---|---|---|
hash |
'_Hash'
|
Hash object |
Source code in libs/shellfish/shellfish/libhash.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
shellfish.libsh
⚓︎
shellfish internals
Modules⚓︎
shellfish.libsh.args
⚓︎
shellfish.libsh.args.arganystr(string: AnyStr) -> AnyStr
⚓︎Return given string with quotes if needed
Examples:
>>> arganystr("a b")
"'a b'"
>>> arganystr("a b c")
"'a b c'"
>>> arganystr(b"a b")
b"'a b'"
Source code in libs/shellfish/shellfish/libsh/args.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
shellfish.libsh.args.args2cmd(args: PopenArgs) -> Union[str, bytes]
⚓︎Return single command string from given popenargs
Examples:
>>> args2cmd(["ls", "-l"])
'ls -l'
>>> args2cmd(["ls", "-l", "a b"])
"ls -l 'a b'"
>>> args2cmd(["ls", "-l", "a b", "c d"])
"ls -l 'a b' 'c d'"
Source code in libs/shellfish/shellfish/libsh/args.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
shellfish.libsh.args.argstr(string: Union[str, bytes]) -> str
⚓︎Return given string with quotes if needed
Examples:
>>> argstr("a b")
"'a b'"
>>> argstr("a b c")
"'a b c'"
>>> argstr(b"a b")
"'a b'"
Source code in libs/shellfish/shellfish/libsh/args.py
28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
shellfish.libsh.args.flatten_args(*args: PopenArgs) -> List[str]
⚓︎Flatten possibly nested iterables of sequences to a list of strings
Examples:
>>> list(flatten_args("cmd", ["uno", "dos", "tres"]))
['cmd', 'uno', 'dos', 'tres']
>>> list(flatten_args("cmd", ["uno", "dos", "tres", ["4444", "five"]]))
['cmd', 'uno', 'dos', 'tres', '4444', 'five']
Source code in libs/shellfish/shellfish/libsh/args.py
43 44 45 46 47 48 49 50 51 52 53 |
|
shellfish.osfs
⚓︎
Os specific filesystem utils/operations
Classes⚓︎
shellfish.osfs.LIN
⚓︎
Bases: OsFsAbc
Linux (and Mac) shell commands/methods container
shellfish.osfs.LIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
str
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
shellfish.osfs.LIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
shellfish.osfs.LIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
Allow links to already exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
|
shellfish.osfs.LIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exist_ok
|
bool
|
Allow links to already exist |
False
|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
Source code in libs/shellfish/shellfish/osfs.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
shellfish.osfs.LIN.unlink_dir(link: str) -> None
staticmethod
⚓︎Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
133 134 135 136 137 138 139 140 141 |
|
shellfish.osfs.LIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
143 144 145 146 147 148 149 150 151 152 |
|
shellfish.osfs.LIN.unlink_file(link: str) -> None
staticmethod
⚓︎Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
154 155 156 157 158 159 160 161 162 |
|
shellfish.osfs.LIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
164 165 166 167 168 169 170 171 172 173 |
|
shellfish.osfs.OsFsAbc
⚓︎
Bases: ABC
Abstract base class for OS-specific fns
shellfish.osfs.WIN
⚓︎
Bases: OsFsAbc
Windows shell commands/methods container
shellfish.osfs.WIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
shellfish.osfs.WIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link(s) exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
shellfish.osfs.WIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
shellfish.osfs.WIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
shellfish.osfs.WIN.unlink_dir(link: str) -> None
staticmethod
⚓︎Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
269 270 271 272 273 274 275 276 277 278 279 280 |
|
shellfish.osfs.WIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.osfs.WIN.unlink_file(link: str) -> None
staticmethod
⚓︎Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
298 299 300 301 302 303 304 305 306 307 308 309 |
|
shellfish.osfs.WIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
Modules⚓︎
shellfish.process
⚓︎
Current running process info
Classes⚓︎
shellfish.process.Env
⚓︎
Env with attr access
Examples:
>>> from os import environ
>>> if 'SOMEENVVARIABLE' in environ:
... del environ['SOMEENVVARIABLE']
>>> environ.get('SOMEENVVARIABLE') # Does not exist in environ
>>> Env.SOMEENVVARIABLE
>>> Env.SOMEENVVARIABLE = 'value'
>>> Env.SOMEENVVARIABLE
'value'
>>> environ.get('SOMEENVVARIABLE')
'value'
>>> environ['SOMEENVVARIABLE']
'value'
>>> 'SOMEENVVARIABLE' in Env
True
>>> {k: v for k, v in Env.items() if k == 'SOMEENVVARIABLE'}
{'SOMEENVVARIABLE': 'value'}
>>> del Env['SOMEENVVARIABLE']
>>> 'SOMEENVVARIABLE' in Env
False
Functions⚓︎
shellfish.process.env_dict() -> Dict[str, str]
⚓︎
Return the current environment-variables as a dictionary
Source code in libs/shellfish/shellfish/process.py
170 171 172 |
|
shellfish.process.hostname() -> str
⚓︎
Return the current computer's hostname
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
hostname |
Examples:
>>> hn = hostname()
>>> isinstance(hn, str)
True
Source code in libs/shellfish/shellfish/process.py
278 279 280 281 282 283 284 285 286 287 288 289 290 |
|
shellfish.process.is_cpython() -> bool
⚓︎
Return True if running on CPython; False otherwise
Source code in libs/shellfish/shellfish/process.py
247 248 249 |
|
shellfish.process.is_mac() -> bool
⚓︎
Determine if current operating system is macos/osx
Returns:
Type | Description |
---|---|
bool
|
True if on a mac; False otherwise |
Source code in libs/shellfish/shellfish/process.py
175 176 177 178 179 180 181 182 |
|
shellfish.process.is_notebook() -> bool
⚓︎
Determine if running in ipython/jupyter notebook; returns True/False
Source code in libs/shellfish/shellfish/process.py
228 229 230 231 232 233 234 235 236 237 238 239 |
|
shellfish.process.is_pypy() -> bool
⚓︎
Return True if running on pypy3; False otherwise
Source code in libs/shellfish/shellfish/process.py
242 243 244 |
|
shellfish.process.is_win() -> bool
⚓︎
Determine if current operating system is windows
Returns:
Type | Description |
---|---|
bool
|
True if on a windows machine; False otherwise |
Source code in libs/shellfish/shellfish/process.py
190 191 192 193 194 195 196 197 |
|
shellfish.process.is_wsl() -> bool
⚓︎
Return True if python is running under (WSL); Return False otherwise
Source code in libs/shellfish/shellfish/process.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
shellfish.process.ismac() -> bool
⚓︎
Alias for is_mac()
Source code in libs/shellfish/shellfish/process.py
185 186 187 |
|
shellfish.process.iswin() -> bool
⚓︎
Alias for is_win()
Source code in libs/shellfish/shellfish/process.py
200 201 202 |
|
shellfish.process.iswsl() -> bool
⚓︎
Alias for is_wsl()
Source code in libs/shellfish/shellfish/process.py
223 224 225 |
|
shellfish.process.linux_version() -> str
⚓︎
Return rhel7 or rhel8 based on the current linux version
Source code in libs/shellfish/shellfish/process.py
263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
shellfish.process.opsys() -> str
⚓︎
Return the current process' os type: 'mac' | 'lin' | 'win' | 'wsl'
Source code in libs/shellfish/shellfish/process.py
252 253 254 255 256 257 258 259 260 |
|
shellfish.process.sys_path_sep() -> str
⚓︎
Return the system path separator string (; on windows -- : otherwise)
Examples:
>>> import os
>>> sep = sys_path_sep()
>>> isinstance(sep, str)
True
>>> os.pathsep == sep
True
Source code in libs/shellfish/shellfish/process.py
293 294 295 296 297 298 299 300 301 302 303 304 305 |
|
shellfish.process.syspath_paths(syspath: Optional[str] = None) -> List[str]
⚓︎
Return the current sys.path as a list
Examples:
>>> sys_paths = syspath_paths()
>>> isinstance(sys_paths, list)
True
>>> sys_path_arg = 'path1;path2;path3' if is_win() else 'path1:path2:path3'
>>> sys_paths_w_args = syspath_paths(syspath=sys_path_arg)
>>> isinstance(sys_paths_w_args, list)
True
>>> sys_paths_w_args == ['path1', 'path2', 'path3']
True
Source code in libs/shellfish/shellfish/process.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
shellfish.process.tmpenv(**kwargs: str) -> Generator[Type[Env], Any, None]
⚓︎
Context manager for Env
Source code in libs/shellfish/shellfish/process.py
57 58 59 60 61 62 63 64 65 66 67 |
|
shellfish.psu
⚓︎
psutils-utils
shellfish.sh
⚓︎
shell utils
Classes⚓︎
shellfish.sh.Done(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
PRun => 'ProcessRun' for finished processes
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
shellfish.sh.Done.__property_fields__: Set[str]
property
⚓︎Returns a set of property names for the class that have a setter
shellfish.sh.Done.__contains__(key: _KT) -> bool
⚓︎Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.sh.Done.__ge__(filepath: FsPath) -> 'Done'
⚓︎Operator overload for writing stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
659 660 661 662 663 664 665 666 667 668 669 670 |
|
shellfish.sh.Done.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.sh.Done.__getattr__(item: _KT) -> Any
⚓︎Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.sh.Done.__gt__(filepath: FsPath) -> None
⚓︎Operator overload for writing a stdout to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
650 651 652 653 654 655 656 657 |
|
shellfish.sh.Done.__irshift__(filepath: FsPath) -> 'Done'
⚓︎Operator overload for appending stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
681 682 683 684 685 686 687 688 689 690 691 692 |
|
shellfish.sh.Done.__post_init__() -> None
⚓︎Write the stdout/stdout to sys.stdout/sys.stderr post object init
Source code in libs/shellfish/shellfish/sh.py
538 539 540 541 |
|
shellfish.sh.Done.__rshift__(filepath: FsPath) -> None
⚓︎Operator overload for appending stdout to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
672 673 674 675 676 677 678 679 |
|
shellfish.sh.Done.__setitem__(key: _KT, value: _VT) -> None
⚓︎Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.sh.Done.asdict() -> Dict[_KT, Any]
⚓︎Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.sh.Done.check(ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0) -> None
⚓︎Check returncode and stderr
Raises:
Type | Description |
---|---|
DoneError
|
If return code is non-zero and stderr is not None |
Source code in libs/shellfish/shellfish/sh.py
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
|
shellfish.sh.Done.completed_process() -> CompletedProcess[str]
⚓︎Return subprocess.CompletedProcess object
Source code in libs/shellfish/shellfish/sh.py
631 632 633 634 635 636 637 638 |
|
shellfish.sh.Done.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.sh.Done.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.sh.Done.done_dict() -> DoneDict
⚓︎Return Done object as typed-dict
Source code in libs/shellfish/shellfish/sh.py
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
|
shellfish.sh.Done.done_obj() -> DoneObj
⚓︎Return Done object typed dict
Source code in libs/shellfish/shellfish/sh.py
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
|
shellfish.sh.Done.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.sh.Done.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.sh.Done.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.sh.Done.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.sh.Done.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.sh.Done.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.sh.Done.eject() -> Dict[_KT, _VT]
⚓︎Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.sh.Done.entries() -> ItemsView[_KT, _VT]
⚓︎Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.sh.Done.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.sh.Done.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.sh.Done.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.sh.Done.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.sh.Done.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.sh.Done.grep(string: str) -> List[str]
⚓︎Return lines in stdout that have
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
String to search for |
required |
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of strings of stdout lines containing the given search string |
Source code in libs/shellfish/shellfish/sh.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 |
|
shellfish.sh.Done.has_required_fields() -> bool
classmethod
⚓︎Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.sh.Done.is_default() -> bool
⚓︎Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.sh.Done.items() -> ItemsView[_KT, _VT]
⚓︎Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.sh.Done.json(*args: Any, **kwargs: Any) -> str
⚓︎Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.sh.Done.json_parse(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
706 707 708 709 710 711 712 713 714 715 716 717 718 |
|
shellfish.sh.Done.json_parse_stderr(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎Return json parsed stderr
Source code in libs/shellfish/shellfish/sh.py
700 701 702 703 704 |
|
shellfish.sh.Done.json_parse_stdout(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
694 695 696 697 698 |
|
shellfish.sh.Done.keys() -> KeysView[_KT]
⚓︎Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.sh.Done.parse_json(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎Return json parsed stdout (alias bc I keep flip-flopping the fn name)
Source code in libs/shellfish/shellfish/sh.py
720 721 722 723 724 725 726 727 728 |
|
shellfish.sh.Done.recurse() -> None
⚓︎Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.sh.Done.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.sh.Done.sys_print() -> None
⚓︎Write self.stdout to sys.stdout and self.stderr to sys.stderr
Source code in libs/shellfish/shellfish/sh.py
616 617 618 619 |
|
shellfish.sh.Done.to_dict() -> Dict[str, Any]
⚓︎Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.sh.Done.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.sh.Done.to_dict_filter_none() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.sh.Done.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.sh.Done.to_json_dict() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.sh.Done.to_json_obj() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.sh.Done.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.sh.Done.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.sh.Done.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.sh.Done.write_stderr(filepath: FsPath, *, append: bool = False) -> None
⚓︎Write stderr as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
640 641 642 643 644 645 646 647 648 |
|
shellfish.sh.Done.write_stdout(filepath: FsPath, *, append: bool = False) -> None
⚓︎Write stdout as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
621 622 623 624 625 626 627 628 629 |
|
shellfish.sh.DoneError(done: Done)
⚓︎
Bases: SubprocessError
Raised when run() is called with check=True and the process returns a non-zero exit status.
Attributes:
Name | Type | Description |
---|---|---|
cmd |
str
|
command that was run |
returncode |
int
|
exit status of the process |
stdout |
str
|
standard output (stdout) of the process |
stderr |
str
|
standard error (stderr) of the process |
Source code in libs/shellfish/shellfish/sh.py
462 463 464 465 466 467 468 |
|
shellfish.sh.DoneObj
⚓︎
Bases: TypedDict
Todo
deprecate this in favor of DoneDict
shellfish.sh.Flag
⚓︎
Flag obj
Examples:
>>> Flag.__help
'--help'
>>> Flag._v
'-v'
shellfish.sh.FlagMeta
⚓︎
Bases: type
Meta class
shellfish.sh.FlagMeta.attr2flag(string: str) -> str
cached
staticmethod
⚓︎Convert and return attr to string
Source code in libs/shellfish/shellfish/sh.py
355 356 357 358 359 |
|
shellfish.sh.HrTime(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
High resolution time
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
shellfish.sh.HrTime.__property_fields__: Set[str]
property
⚓︎Returns a set of property names for the class that have a setter
shellfish.sh.HrTime.__contains__(key: _KT) -> bool
⚓︎Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.sh.HrTime.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.sh.HrTime.__getattr__(item: _KT) -> Any
⚓︎Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.sh.HrTime.__post_init__() -> Any
⚓︎Function place holder that is called after object initialization
Source code in libs/jsonbourne/jsonbourne/pydantic.py
98 99 |
|
shellfish.sh.HrTime.__setitem__(key: _KT, value: _VT) -> None
⚓︎Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.sh.HrTime.asdict() -> Dict[_KT, Any]
⚓︎Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.sh.HrTime.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.sh.HrTime.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.sh.HrTime.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.sh.HrTime.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.sh.HrTime.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.sh.HrTime.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.sh.HrTime.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.sh.HrTime.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.sh.HrTime.eject() -> Dict[_KT, _VT]
⚓︎Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.sh.HrTime.entries() -> ItemsView[_KT, _VT]
⚓︎Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.sh.HrTime.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.sh.HrTime.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.sh.HrTime.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.sh.HrTime.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.sh.HrTime.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.sh.HrTime.from_seconds(seconds: float) -> 'HrTime'
classmethod
⚓︎Return HrTime object from seconds
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
'HrTime'
|
HrTime object |
Source code in libs/shellfish/shellfish/sh.py
417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
shellfish.sh.HrTime.has_required_fields() -> bool
classmethod
⚓︎Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.sh.HrTime.is_default() -> bool
⚓︎Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.sh.HrTime.items() -> ItemsView[_KT, _VT]
⚓︎Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.sh.HrTime.json(*args: Any, **kwargs: Any) -> str
⚓︎Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.sh.HrTime.keys() -> KeysView[_KT]
⚓︎Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.sh.HrTime.recurse() -> None
⚓︎Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.sh.HrTime.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.sh.HrTime.to_dict() -> Dict[str, Any]
⚓︎Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.sh.HrTime.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.sh.HrTime.to_dict_filter_none() -> Dict[str, Any]
⚓︎Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.sh.HrTime.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.sh.HrTime.to_json_dict() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.sh.HrTime.to_json_obj() -> JsonObj[Any]
⚓︎Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.sh.HrTime.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.sh.HrTime.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.sh.HrTime.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.sh.HrTimeDict
⚓︎
Bases: TypedDict
High resolution time
shellfish.sh.HrTimeObj
⚓︎
Bases: TypedDict
Todo
deprecate this in favor of HrTimeDict
shellfish.sh.LIN
⚓︎
Bases: LIN
Linux (and Mac) shell commands/methods container
shellfish.sh.LIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
str
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
shellfish.sh.LIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
shellfish.sh.LIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
Allow links to already exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
|
shellfish.sh.LIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exist_ok
|
bool
|
Allow links to already exist |
False
|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
Source code in libs/shellfish/shellfish/osfs.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
shellfish.sh.LIN.rsync(src: str, dest: str, delete: bool = False, mkdirs: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> Done
staticmethod
⚓︎Run an rsync
subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mkdirs
|
bool
|
Make destination directories if they do not already exist; defaults to False. |
False
|
src
|
str
|
Source directory path |
required |
dest
|
str
|
Destination directory path |
required |
delete
|
bool
|
Delete files/directories in destination if they do exist in source |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Name | Type | Description |
---|---|---|
Done |
Done
|
Done object containing the info for the rsync run |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 |
|
shellfish.sh.LIN.rsync_args(src: str, dest: str, delete: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> List[str]
staticmethod
⚓︎Return args for rsync command on linux/mac
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to remote (raid) tdir |
required |
dest
|
str
|
path to local tdir |
required |
delete
|
bool
|
Flag that will do a 'hard sync' |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from rsync |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 |
|
shellfish.sh.LIN.unlink_dir(link: str) -> None
staticmethod
⚓︎Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
133 134 135 136 137 138 139 140 141 |
|
shellfish.sh.LIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
143 144 145 146 147 148 149 150 151 152 |
|
shellfish.sh.LIN.unlink_file(link: str) -> None
staticmethod
⚓︎Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
154 155 156 157 158 159 160 161 162 |
|
shellfish.sh.LIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
164 165 166 167 168 169 170 171 172 173 |
|
shellfish.sh.Stdio
⚓︎
Bases: IntEnum
Standard-io enum object
shellfish.sh.WIN
⚓︎
Bases: WIN
Windows shell commands/methods container
shellfish.sh.WIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
shellfish.sh.WIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link(s) exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
shellfish.sh.WIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
shellfish.sh.WIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
shellfish.sh.WIN.robocopy(src: str, dest: str, *, mkdirs: bool = True, delete: bool = False, exclude_files: Optional[Iterable[str]] = None, exclude_dirs: Optional[Iterable[str]] = None, dry_run: bool = False) -> Done
staticmethod
⚓︎Robocopy wrapper function (crude in that it opens a subprocess)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
mkdirs
|
bool
|
Flag to make destinaation directories if they do not already exist |
True
|
Returns:
Type | Description |
---|---|
Done
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 |
|
shellfish.sh.WIN.robocopy_args(src: str, dest: str, *, delete: bool = False, exclude_files: Optional[List[str]] = None, exclude_dirs: Optional[List[str]] = None, dry_run: bool = False) -> List[str]
staticmethod
⚓︎Return list of robocopy command args
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[List[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[List[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 |
|
shellfish.sh.WIN.unlink_dir(link: str) -> None
staticmethod
⚓︎Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
269 270 271 272 273 274 275 276 277 278 279 280 |
|
shellfish.sh.WIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.sh.WIN.unlink_file(link: str) -> None
staticmethod
⚓︎Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
298 299 300 301 302 303 304 305 306 307 308 309 |
|
shellfish.sh.WIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
Functions⚓︎
shellfish.sh.basename(fspath: FsPath) -> str
⚓︎
Return the basename of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 |
|
shellfish.sh.cd(dirpath: FsPath) -> None
⚓︎
Change directory to given dirpath; alias for os.chdir
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory fspath |
required |
Source code in libs/shellfish/shellfish/sh.py
1886 1887 1888 1889 1890 1891 1892 1893 |
|
shellfish.sh.chmod(fspath: FsPath, mode: int) -> None
⚓︎
Change the access permissions of a file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file to chmod |
required |
mode
|
int
|
Permissions mode as an int |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
shellfish.sh.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str]
⚓︎
Copy a file given a source-path and a destination-path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source fspath |
required |
dest
|
str
|
Destination fspath |
required |
dryrun
|
bool
|
Do not copy file if True just return the src and dest |
False
|
mkdirp
|
bool
|
Create parent directories if they do not exist |
False
|
Source code in libs/shellfish/shellfish/fs/__init__.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
shellfish.sh.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None
⚓︎
Copy the directory/file src to the directory/file dest
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source directory/file to copy |
required |
dest
|
FsPath
|
Destination directory/file to copy |
required |
force
|
bool
|
Force the copy (like -f flag for cp in shell) |
True
|
recursive
|
bool
|
Recursive copy (like -r flag for cp in shell) |
False
|
r
|
bool
|
alias for recursive |
False
|
f
|
bool
|
alias for force |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If src is a directory and recursive and r are both |
Source code in libs/shellfish/shellfish/fs/__init__.py
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
|
shellfish.sh.decode_stdio_bytes(stdio_bytes: Union[str, bytes], lf: bool = True) -> str
⚓︎
Return Stdio bytes from stdout/stderr as a string
Args:
stdio_bytes (bytes): STDOUT/STDERR bytes
lf (bool): Replace `
line endings with
`
Returns:
str: decoded stdio bytes
Source code in libs/shellfish/shellfish/sh.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
shellfish.sh.dir_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
123 124 125 |
|
shellfish.sh.dir_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.sh.dirname(fspath: FsPath) -> str
⚓︎
Return dirname/parent-dir of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 |
|
shellfish.sh.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all dirpaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
|
shellfish.sh.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield directory-paths beneath a dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
shellfish.sh.do(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[FsPath] = None, shell: bool = False, check: bool = False, tee: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
tee
|
bool
|
Flag to tee the subprocess stdout and stderr to sys.stdout/stderr |
False
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check against |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
if args and *popenargs are both given |
Source code in libs/shellfish/shellfish/sh.py
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
|
shellfish.sh.do_async(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
If both *popenargs and args are given |
Source code in libs/shellfish/shellfish/sh.py
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
|
shellfish.sh.do_asyncify(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess asynchronously using asyncified version of do
Source code in libs/shellfish/shellfish/sh.py
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
shellfish.sh.doa(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Alias for sh.do_async
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 |
|
shellfish.sh.echo(*objects: Any, sep: str = ' ', end: str = '\n', file: Optional[IO[str]] = None, flush: bool = False) -> None
⚓︎
Print/echo function
Args:
*objects: Item(s) to print/echo
sep: Separator to print with
end: End of print suffix; defaults to `
` file: File like object to write to if not stdout flush: Flush the file after writing
Examples:
>>> echo("shellfish")
shellfish
Source code in libs/shellfish/shellfish/echo.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
shellfish.sh.exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
113 114 115 |
|
shellfish.sh.export(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
if unable to parse key/val |
Source code in libs/shellfish/shellfish/sh.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 |
|
shellfish.sh.extension(fspath: str, *, period: bool = False) -> str
⚓︎
Return the extension for a fspath
Examples:
>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/shellfish/fs/__init__.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
|
shellfish.sh.file_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
118 119 120 |
|
shellfish.sh.file_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.sh.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]
⚓︎
Yield lines from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
File to yield lines from |
required |
keepends
|
bool
|
Flag to keep the ends of the file lines |
True
|
Yields:
Type | Description |
---|---|
Iterable[str]
|
Lines from the given fspath |
Examples:
>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
... file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
... file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
shellfish.sh.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool
⚓︎
Compare 2 files for equality given their filepaths
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left
|
FsPath
|
Filepath 1 |
required |
right
|
FsPath
|
Filepath 2 |
required |
shallow
|
bool
|
Check only size and modification time if True |
True
|
blocksize
|
int
|
Chunk size to read files |
65536
|
Returns:
Type | Description |
---|---|
bool
|
True if files are equal, False otherwise |
Source code in libs/shellfish/shellfish/fs/__init__.py
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
shellfish.sh.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
|
shellfish.sh.filepath_mtimedelta_sec(filepath: FsPath) -> float
⚓︎
Return the seconds since the file(path) was last modified
Source code in libs/shellfish/shellfish/fs/__init__.py
378 379 380 |
|
shellfish.sh.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]]
⚓︎
Return a files_gen() and a dirs_gen() in one swell-foop
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath is a directory |
True
|
Returns:
Type | Description |
---|---|
Tuple[Iterator[str], Iterator[str]]
|
A tuple of two generators (files_gen(), dirs_gen()) |
Examples:
>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2a']
>>> _files, _dirs = files_dirs_gen(tmpdir)
>>> _files = list(_files)
>>> _dirs = list(_dirs)
>>> files_n_dirs_list = list(sorted(set(_files + _dirs)))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
shellfish.sh.files_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield file-paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields file-paths (absolute or relative) |
Examples:
>>> tmpdir = 'files_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt',
'files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt']
>>> files_list = list(sorted(set(files_gen(tmpdir))))
>>> files_list = [el.replace('\\', '/') for el in files_list]
>>> pprint(files_list)
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> pprint(list(sorted(set(expected_files))))
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> list(sorted(set(files_list))) == list(sorted(set(expected_files)))
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
shellfish.sh.filesize(fspath: FsPath) -> int
⚓︎
Return the size of the given file(path) in bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath as a string or pathlib.Path object |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
size of the fspath in bytes |
Source code in libs/shellfish/shellfish/fs/__init__.py
163 164 165 166 167 168 169 170 171 172 173 |
|
shellfish.sh.filesize_async(fspath: FsPath) -> int
async
⚓︎
Return the size of the file at the given fspath
Examples:
>>> from asyncio import run as aiorun
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmpdir:
... tmpdir = Path(tmpdir)
... fpath = tmpdir / "test.txt"
... written = fpath.write_text("hello world")
... aiorun(filesize_async(fpath))
11
Source code in libs/shellfish/shellfish/fs/_async.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
shellfish.sh.flatten_args(*args: Union[Any, List[Any]]) -> List[str]
⚓︎
Flatten possibly nested iterables of sequences to a list of strings
Examples:
>>> list(flatten_args("cmd", ["uno", "dos", "tres"]))
['cmd', 'uno', 'dos', 'tres']
>>> list(flatten_args("cmd", ["uno", "dos", "tres", ["4444", "five"]]))
['cmd', 'uno', 'dos', 'tres', '4444', 'five']
Source code in libs/shellfish/shellfish/sh.py
834 835 836 837 838 839 840 841 842 843 844 |
|
shellfish.sh.fspath(fspath: FsPath) -> str
⚓︎
Alias for os._fspath; returns fspath string for any type of path
Source code in libs/shellfish/shellfish/fs/__init__.py
93 94 95 |
|
shellfish.sh.glob(pattern: str, *, recursive: bool = False, r: bool = False) -> Iterator[str]
⚓︎
Return an iterator of fspaths matching the given glob pattern
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
Glob pattern |
required |
recursive
|
bool
|
Recursively search directories if True |
False
|
r
|
bool
|
Recursively search directories if True (Alias for recursive) |
False
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Iterator[str]: Iterator of fspaths matching the glob pattern |
Source code in libs/shellfish/shellfish/fs/__init__.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
|
shellfish.sh.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish.sh.is_dir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.sh.is_file(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
133 134 135 |
|
shellfish.sh.is_file_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.sh.is_link(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; alias for islink
Source code in libs/shellfish/shellfish/fs/__init__.py
138 139 140 |
|
shellfish.sh.is_link_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.sh.isdir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
103 104 105 |
|
shellfish.sh.isdir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.sh.isfile(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
98 99 100 |
|
shellfish.sh.isfile_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.sh.islink(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
108 109 110 |
|
shellfish.sh.islink_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.sh.listdir_async(fspath: FsPath) -> List[str]
async
⚓︎
Async version of os.listdir
Source code in libs/shellfish/shellfish/fs/_async.py
133 134 135 |
|
shellfish.sh.listdir_gen(fspath: FsPath = '.', *, abspath: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = False, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[Path]
⚓︎
Return an iterator of strings from DirEntries
Examples >>> tmpdir = 'listdir_gen.doctest' >>> from shellfish import sh >>> from os import makedirs, path, chdir >>> from shutil import rmtree >>> _makedirs(tmpdir, exist_ok=True) >>> pwd = sh.pwd() >>> sh.cd(tmpdir) >>> filepath_parts = [ ... ("dir", "file1.txt"), ... ("dir", "file2.txt"), ... ("dir", "file3.txt"), ... ("dir", "data1.json"), ... ("dir", "dir2", "file1.txt"), ... ("dir", "dir2", "file2.txt"), ... ("dir", "dir2", "file3.txt"), ... ("dir", "dir2a", "file1.txt"), ... ("dir", "dir2a", "file2.txt"), ... ("dir", "dir2a", "file3.txt"), ... ] >>> from shellfish.fs import touch >>> expected_files = [] >>> for f in filepath_parts: ... fspath = path.join(*f) ... fspath = path.join(tmpdir, fspath) ... dirpath = path.dirname(fspath) ... expected_files.append(fspath) ... _makedirs(dirpath, exist_ok=True) ... touch(fspath) >>> dirpath = path.join(tmpdir, 'dir') >>> dirpath.replace("\", "/") 'listdir_gen.doctest/dir' >>> sorted(listdir_gen(dirpath, dirs=False, symlinks=False)) ['data1.json', 'file1.txt', 'file2.txt', 'file3.txt'] >>> abspaths = sorted(listdir_gen(dirpath, abspath=True, dirs=False, symlinks=False)) >>> for abspath in [p.replace("\", "/") for p in abspaths]: ... print(abspath) listdir_gen.doctest/dir/data1.json listdir_gen.doctest/dir/file1.txt listdir_gen.doctest/dir/file2.txt listdir_gen.doctest/dir/file3.txt >>> sh.cd(pwd) >>> import os >>> if path.exists(tmpdir): ... rmtree(tmpdir) >>> path.isdir(tmpdir) False
Source code in libs/shellfish/shellfish/fs/__init__.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
shellfish.sh.ls(dirpath: FsPath = '.', abspath: bool = False) -> List[str]
⚓︎
List files and dirs given a dirpath (defaults to pwd)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
path-string to directory to list |
'.'
|
abspath
|
bool
|
Give absolute paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of the directory items |
Source code in libs/shellfish/shellfish/sh.py
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 |
|
shellfish.sh.ls_async(dirpath: FsPath = '.', abspath: bool = False) -> List[str]
async
⚓︎
List files and dirs given a dirpath (defaults to pwd)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
path-string to directory to list |
'.'
|
abspath
|
bool
|
Give absolute paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of the directory items |
Source code in libs/shellfish/shellfish/sh.py
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 |
|
shellfish.sh.ls_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the directories in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want list directories |
'.'
|
abspath
|
bool
|
Return absolute directory paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of directories as strings |
Source code in libs/shellfish/shellfish/sh.py
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 |
|
shellfish.sh.ls_files(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the files in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want to list files |
'.'
|
abspath
|
bool
|
Return absolute filepaths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of files as strings |
Source code in libs/shellfish/shellfish/sh.py
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 |
|
shellfish.sh.ls_files_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> Tuple[List[str], List[str]]
⚓︎
List the files and directories given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to execute on |
'.'
|
abspath
|
bool
|
Return absolute file/directory paths |
False
|
Returns:
Type | Description |
---|---|
Tuple[List[str], List[str]]
|
Two lists of strings; the first is a list of the files and the second is a list of the directories |
Source code in libs/shellfish/shellfish/sh.py
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 |
|
shellfish.sh.lstat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.sh.mkdir(fspath: FsPath, *, parents: bool = False, p: bool = False, exist_ok: bool = False) -> None
⚓︎
Make directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to create |
required |
parents
|
bool
|
Make parent dirs if True; do not make parent dirs if False |
False
|
p
|
bool
|
Make parent dirs if True; do not make parent dirs if False (alias of parents) |
False
|
exist_ok
|
bool
|
Throw error if directory exists and exist_ok is False |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
|
shellfish.sh.mkdirp(fspath: FsPath) -> None
⚓︎
Make directory and parents
Source code in libs/shellfish/shellfish/fs/__init__.py
1435 1436 1437 |
|
shellfish.sh.move(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 |
|
shellfish.sh.mv(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/sh.py
2211 2212 2213 2214 2215 2216 2217 2218 2219 |
|
shellfish.sh.path_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 |
|
shellfish.sh.pstderr(proc: CompletedProcess[AnyStr]) -> str
⚓︎
Get the STDERR as a string from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
python subprocess.process object with STDERR |
required |
Returns:
Type | Description |
---|---|
str
|
STDERR for the proc as string |
Source code in libs/shellfish/shellfish/sh.py
790 791 792 793 794 795 796 797 798 799 800 801 802 |
|
shellfish.sh.pstdout(proc: CompletedProcess[AnyStr]) -> str
⚓︎
Get the STDOUT as a string from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
python subprocess.process object with stdout |
required |
Returns:
Type | Description |
---|---|
str
|
STDOUT for the proc as string |
Source code in libs/shellfish/shellfish/sh.py
775 776 777 778 779 780 781 782 783 784 785 786 787 |
|
shellfish.sh.pstdout_pstderr(proc: CompletedProcess[AnyStr]) -> Tuple[str, str]
⚓︎
Get the STDOUT and STDERR as strings from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
Completed-subprocess |
required |
Returns:
Type | Description |
---|---|
Tuple[str, str]
|
Tuple of two strings: (stdout-string, stderr-string) |
Source code in libs/shellfish/shellfish/sh.py
805 806 807 808 809 810 811 812 813 814 815 |
|
shellfish.sh.pwd() -> str
⚓︎
Return present-working-directory path string; alias for os.getcwd
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
present working directory as string |
Examples:
>>> import os
>>> pwd() == os.getcwd()
True
Source code in libs/shellfish/shellfish/sh.py
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 |
|
shellfish.sh.q(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> q("hello world")
"'hello world'"
>>> q("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 |
|
shellfish.sh.quote(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> quote("hello world")
"'hello world'"
>>> quote("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 |
|
shellfish.sh.rbytes(filepath: FsPath) -> bytes
⚓︎
Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "rbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> wbytes(fspath, bites_to_save)
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
shellfish.sh.rbytes_async(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.sh.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> Iterable[bytes]
⚓︎
Yield bytes from a given fspath
Source code in libs/shellfish/shellfish/fs/__init__.py
1061 1062 1063 1064 1065 1066 1067 1068 |
|
shellfish.sh.rbytes_gen_async(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.sh.rjson(filepath: FsPath) -> Any
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
|
shellfish.sh.rjson_async(filepath: FsPath) -> Any
async
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
shellfish.sh.rm(fspath: FsPath, *, force: bool = False, recursive: bool = False, verbose: bool = False, f: bool = False, r: bool = False, v: bool = False, dryrun: bool = False) -> None
⚓︎
Remove files & directories in the style of the shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory to remove |
required |
force
|
bool
|
Flag to force removal; ignore missing |
False
|
recursive
|
bool
|
Flag to remove recursively (like the |
False
|
verbose
|
bool
|
Flag to be verbose |
False
|
f
|
bool
|
alias for force kwarg |
False
|
v
|
bool
|
alias for verbose |
False
|
r
|
bool
|
alias for recursive kwarg |
False
|
dryrun
|
bool
|
Flag to not actually remove anything |
False
|
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/sh.py
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 |
|
shellfish.sh.rm_gen(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False) -> Generator[str, Any, Any]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): Force removal of files and directories
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
shellfish.sh.rmdir(fspath: FsPath, *, force: bool = False, recursive: bool = False) -> None
⚓︎
Remove directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to remove |
required |
force
|
bool
|
Force removal of files and directories |
False
|
recursive
|
bool
|
Recursively remove all contents if True |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
shellfish.sh.rmfile(fspath: FsPath, *, dryrun: bool = False) -> str
⚓︎
Remove a file at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath to remove |
required |
dryrun
|
bool
|
Do not remove file if True |
False
|
Returns:
Type | Description |
---|---|
str
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
|
shellfish.sh.rstring(filepath: FsPath, *, encoding: str = 'utf-8') -> str
⚓︎
Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
Encoding to use for reading the file |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "lstring.doctest.txt"
>>> sstring(fspath, r'Check out this string')
21
>>> lstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
|
shellfish.sh.rstring_async(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.sh.safepath(fspath: FsPath) -> str
⚓︎
Check if a file/dir path is save/unused; returns an unused path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
file-system path; file or directory path string or Path obj |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
file/dir path that does not exist and contains the given path |
Source code in libs/shellfish/shellfish/fs/__init__.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
shellfish.sh.scandir(dirpath: FsPath = '.') -> Iterable[DirEntry[AnyStr]]
⚓︎
Typed version of os.scandir
Source code in libs/shellfish/shellfish/fs/__init__.py
176 177 178 179 180 |
|
shellfish.sh.scandir_gen(fspath: FsPath = '.', *, recursive: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = True, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[DirEntry[str]]
⚓︎
Return an iterator of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
(FsPath): dirpath to look through |
'.'
|
recursive
|
bool
|
recursively scan the directory |
False
|
follow_symlinks
|
bool
|
follow symlinks when checking for dirs and files |
True
|
files
|
bool
|
include files |
True
|
dirs
|
bool
|
include directories |
True
|
symlinks
|
bool
|
include symlinks |
True
|
dirs_only
|
bool
|
only include directories |
False
|
files_only
|
bool
|
only include files |
False
|
symlinks_only
|
bool
|
only include symlinks |
False
|
Returns:
Type | Description |
---|---|
Iterator[DirEntry[str]]
|
Iterator[DirEntry]: Iterator of os.DirEntry objects |
Raises:
Type | Description |
---|---|
ValueError
|
if any of the kwargs ( |
Source code in libs/shellfish/shellfish/fs/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.sh.scandir_list(dirpath: FsPath = '.') -> List[DirEntry[AnyStr]]
⚓︎
Return a list of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Dirpath to scan |
'.'
|
Returns:
Type | Description |
---|---|
List[DirEntry[AnyStr]]
|
List[DirEntry]: List of os.DirEntry objects |
Source code in libs/shellfish/shellfish/fs/__init__.py
183 184 185 186 187 188 189 190 191 192 193 |
|
shellfish.sh.seconds2hrtime(seconds: Union[float, int]) -> Tuple[int, int]
⚓︎
Return hr-time Tuple[int, int] (seconds, nanoseconds)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
Tuple[int, int]
|
Tuple[int, int]: (seconds, nanoseconds) |
Source code in libs/shellfish/shellfish/sh.py
383 384 385 386 387 388 389 390 391 392 393 394 |
|
shellfish.sh.sep_join(path_strings: Iterator[str]) -> str
⚓︎
Join iterable of strings on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1319 1320 1321 |
|
shellfish.sh.sep_lstrip(fspath: FsPath) -> str
⚓︎
Left-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1329 1330 1331 |
|
shellfish.sh.sep_rstrip(fspath: FsPath) -> str
⚓︎
Right-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1334 1335 1336 |
|
shellfish.sh.sep_split(fspath: FsPath) -> Tuple[str, ...]
⚓︎
Split a string on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1314 1315 1316 |
|
shellfish.sh.sep_strip(fspath: FsPath) -> str
⚓︎
Strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1324 1325 1326 |
|
shellfish.sh.setenv(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Returns:
Type | Description |
---|---|
Tuple[str, str]
|
Tuple[str, str]: environment variable key/value pair |
Source code in libs/shellfish/shellfish/sh.py
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 |
|
shellfish.sh.shebang(fspath: FsPath) -> Union[None, str]
⚓︎
Get the shebang string given a fspath; Returns None if no shebang
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file that might have a shebang |
required |
Returns:
Type | Description |
---|---|
Union[None, str]
|
Optional[str]: The shebang string if it exists, None otherwise |
Examples:
>>> from inspect import getabsfile
>>> script = 'ashellscript.sh'
>>> with open(script, 'w') as f:
... f.write('#!/bin/bash\necho "howdy"\n')
25
>>> shebang(script)
'#!/bin/bash'
>>> from os import remove
>>> remove(script)
Source code in libs/shellfish/shellfish/fs/__init__.py
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
|
shellfish.sh.shell(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, shell: bool = True, extenv: bool = True, cwd: Optional[FsPath] = None, check: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously in current shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell; default is True for |
True
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check if ok |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 |
|
shellfish.sh.shplit(string: str, comments: bool = False, posix: bool = True) -> List[str]
⚓︎
Typed alias for shlex.split
Source code in libs/shellfish/shellfish/sh.py
1932 1933 1934 |
|
shellfish.sh.source(filepath: FsPath, _globals: bool = True) -> None
⚓︎
Execute/run a python file given a fspath and put globals in globasl
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Path to python file |
required |
_globals
|
bool
|
Exec using globals |
True
|
Source code in libs/shellfish/shellfish/sh.py
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 |
|
shellfish.sh.stat(fspath: FsPath) -> os_stat_result
⚓︎
Return the os.stat_result object for a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory |
required |
Returns:
Type | Description |
---|---|
stat_result
|
os.stat_result: stat_result object |
Source code in libs/shellfish/shellfish/fs/__init__.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 |
|
shellfish.sh.stat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.sh.touch(fspath: FsPath, *, mkdirp: bool = True) -> None
⚓︎
Create an empty file given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path for where to make an empty file |
required |
mkdirp
|
bool
|
Make parent directories if they don't exist |
True
|
Source code in libs/shellfish/shellfish/fs/__init__.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
shellfish.sh.tree(dirpath: FsPath, filterfn: Optional[Callable[[str], bool]] = None) -> str
⚓︎
Create a directory tree string given a directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory string to make tree for |
required |
filterfn
|
Optional[Callable[[str], bool]]
|
Function to filter sub-directories and sub-files with |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Directory-tree string |
Examples:
>>> tmpdir = 'tree.doctest'
>>> from os import makedirs; makedirs(tmpdir, exist_ok=True)
>>> from pathlib import Path
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... makedirs(dirpath, exist_ok=True)
... Path(fspath).touch()
>>> print(tree(tmpdir))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── file1.txt
├── file2.txt
└── file3.txt
>>> print(tree(tmpdir, lambda s: _DirTree._default_filter(s) and not "file2" in s))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ └── file3.txt
├── file1.txt
└── file3.txt
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/sh.py
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 |
|
shellfish.sh.walk_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield all paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'walk_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f).replace('\\', '/')
... fspath = path.join(tmpdir, fspath).replace('\\', '/')
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = [el.replace('\\', '/') for el in sorted(set(expected_dirs))]
>>> from pprint import pprint
>>> pprint(expected_files)
['walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt']
>>> pprint(expected_dirs)
['walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2a']
>>> walk_gen_list = list(sorted(walk_gen(tmpdir)))
>>> walk_gen_list = [el.replace('\\', '/') for el in walk_gen_list]
>>> pprint(walk_gen_list)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> pprint(expected)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> walk_gen_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
shellfish.sh.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> wbytes(fspath, bites_to_save)
20
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 |
|
shellfish.sh.wbytes_async(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.sh.wbytes_gen(filepath: FsPath, bytes_gen: Iterable[bytes], append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Iterable[bytes]
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes_gen.doctest.txt"
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save # they are bytes!
(b'These are some bytes... ', b'more bytes!')
>>> wbytes_gen(fspath, (b for b in bites_to_save))
35
>>> rbytes(fspath)
b'These are some bytes... more bytes!'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
shellfish.sh.wbytes_gen_async(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.sh.where(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
; alias of shellfish.sh.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 |
|
shellfish.sh.which(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 |
|
shellfish.sh.which_lru(cmd: str, path: Optional[str] = None) -> Optional[str]
cached
⚓︎
Return the result of shutil.which
and cache the results
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 |
|
shellfish.sh.wjson(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, chmod: Optional[int] = None, append: bool = False, **kwargs: Any) -> int
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Append a newline to the end of the file |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
append
|
bool
|
Append to the file if True, overwrite otherwise; default |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dumpb |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 |
|
shellfish.sh.wjson_async(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, append: bool = False, chmod: Optional[int] = None, **kwargs: Any) -> int
async
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dump |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "wjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "wjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
shellfish.sh.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
String encoding to write file with |
'utf-8'
|
append
|
bool
|
Flag to append to file; default = False |
False
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "sstring.doctest.txt"
>>> wstring(fspath, r'Check out this string')
21
>>> rstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
shellfish.sh.wstring_async(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
Modules⚓︎
shellfish.sp
⚓︎
Classes⚓︎
shellfish.sp.ProcessDt(ti: float, tf: float, dt: float)
dataclass
⚓︎
Process time delta dataclass
Examples:
>>> from shellfish.sp import ProcessDt
>>> ti = 0
>>> tf = 1
>>> dt = ProcessDt.from_titf(ti=ti, tf=tf)
>>> dt
ProcessDt(ti=0, tf=1, dt=1)
Functions⚓︎
shellfish.sp.completed_process_dict(completed_process: CompletedProcess[str]) -> CompletedProcessDict
⚓︎
Convert CompletedProcess to CompletedProcessObj (typed dict)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completed_process
|
CompletedProcess[str]
|
CompletedProcess object |
required |
Returns:
Type | Description |
---|---|
CompletedProcessDict
|
CompletedProcessObj typed dict |
Examples:
>>> from subprocess import CompletedProcess
>>> from shellfish.sp import completed_process_dict
>>> cp = CompletedProcess(
... args=['some', 'args'],
... stdout="stdout string",
... stderr="stderr string",
... returncode=0
... )
>>> from pprint import pprint
>>> cp_typed_dict = completed_process_dict(completed_process=cp)
>>> pprint(cp_typed_dict)
{'args': ['some', 'args'],
'returncode': 0,
'stderr': 'stderr string',
'stdout': 'stdout string'}
Source code in libs/shellfish/shellfish/sp.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
|
shellfish.sp.pcheck(process: CompletedProcess[Any], ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0) -> None
⚓︎
Parameters:
Name | Type | Description | Default |
---|---|---|---|
process
|
CompletedProcess[Any]
|
CompletedProcess object |
required |
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
OK code or sequence of codes, default is 0 |
0
|
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
CompletedProcessError
|
if process.returncode not in ok_code |
Source code in libs/shellfish/shellfish/sp.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
|
shellfish.sp.runs(args: PopenArgs, *, executable: Optional[str] = None, stdin: Optional[Union[IO[Any], int]] = None, input: Optional[str] = None, stdout: Optional[Union[IO[Any], int]] = None, stderr: Optional[Union[IO[Any], int]] = None, shell: bool = False, cwd: Optional[FsPath] = None, timeout: Optional[float] = None, capture_output: bool = False, check: bool = False, env: Optional[Mapping[str, str]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, **other_popen_kwargs: Any) -> CompletedProcess[str]
⚓︎
Run command with txt output
Source code in libs/shellfish/shellfish/sp.py
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.stdio
⚓︎
shellfish.testing
⚓︎
Functions⚓︎
shellfish.testing.mk_random_dirtree(dest: Optional[str] = None, n_subdirectories: int = 8, max_subdirectory_files: int = 4, max_file_string_len: int = 100) -> Dict[str, List[str]]
⚓︎
Make a random directory tree full of dummy files at a given dirpath
Source code in libs/shellfish/shellfish/testing.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
shellfish.testing.random_directory_path(depth: int = 4) -> str
⚓︎
Return a random directory path with a given depth (defaults to 4)
Examples:
>>> from os import sep
>>> dirpath = random_directory_path(4)
>>> len(dirpath.split(sep)) == 4
True
Source code in libs/shellfish/shellfish/testing.py
50 51 52 53 54 55 56 57 58 59 60 |
|
shellfish.testing.random_string(length: int = 10) -> str
⚓︎
Return a random string of a given length (defaults to 10)
Examples:
>>> string = random_string(10)
>>> len(string) == 10
True
Source code in libs/shellfish/shellfish/testing.py
36 37 38 39 40 41 42 43 44 45 46 47 |
|
shellfish.tests
⚓︎
shellfish dist tests
Modules⚓︎
shellfish.tests.test_fs
⚓︎
Testing shelfish.fs
shellfish.tests.test_fs.test_is_file_dir_link(tmp_path: Path) -> None
⚓︎Test is_file
Source code in libs/shellfish/shellfish/tests/test_fs.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
shellfish.tests.test_fs.test_is_file_dir_link_async(tmp_path: Path) -> None
async
⚓︎Test is_file
Source code in libs/shellfish/shellfish/tests/test_fs.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
|
shellfish.fs
⚓︎
file-system utils
Classes⚓︎
shellfish.fs.Stdio
⚓︎
Bases: IntEnum
Standard-io enum object
Functions⚓︎
shellfish.fs.chmod(fspath: FsPath, mode: int) -> None
⚓︎
Change the access permissions of a file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file to chmod |
required |
mode
|
int
|
Permissions mode as an int |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
shellfish.fs.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str]
⚓︎
Copy a file given a source-path and a destination-path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source fspath |
required |
dest
|
str
|
Destination fspath |
required |
dryrun
|
bool
|
Do not copy file if True just return the src and dest |
False
|
mkdirp
|
bool
|
Create parent directories if they do not exist |
False
|
Source code in libs/shellfish/shellfish/fs/__init__.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
shellfish.fs.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None
⚓︎
Copy the directory/file src to the directory/file dest
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source directory/file to copy |
required |
dest
|
FsPath
|
Destination directory/file to copy |
required |
force
|
bool
|
Force the copy (like -f flag for cp in shell) |
True
|
recursive
|
bool
|
Recursive copy (like -r flag for cp in shell) |
False
|
r
|
bool
|
alias for recursive |
False
|
f
|
bool
|
alias for force |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If src is a directory and recursive and r are both |
Source code in libs/shellfish/shellfish/fs/__init__.py
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
|
shellfish.fs.dir_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
123 124 125 |
|
shellfish.fs.dir_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.fs.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all dirpaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
|
shellfish.fs.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield directory-paths beneath a dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
shellfish.fs.exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
113 114 115 |
|
shellfish.fs.extension(fspath: str, *, period: bool = False) -> str
⚓︎
Return the extension for a fspath
Examples:
>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/shellfish/fs/__init__.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
|
shellfish.fs.file_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
118 119 120 |
|
shellfish.fs.file_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.fs.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]
⚓︎
Yield lines from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
File to yield lines from |
required |
keepends
|
bool
|
Flag to keep the ends of the file lines |
True
|
Yields:
Type | Description |
---|---|
Iterable[str]
|
Lines from the given fspath |
Examples:
>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
... file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
... file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
shellfish.fs.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool
⚓︎
Compare 2 files for equality given their filepaths
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left
|
FsPath
|
Filepath 1 |
required |
right
|
FsPath
|
Filepath 2 |
required |
shallow
|
bool
|
Check only size and modification time if True |
True
|
blocksize
|
int
|
Chunk size to read files |
65536
|
Returns:
Type | Description |
---|---|
bool
|
True if files are equal, False otherwise |
Source code in libs/shellfish/shellfish/fs/__init__.py
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
shellfish.fs.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
|
shellfish.fs.filepath_mtimedelta_sec(filepath: FsPath) -> float
⚓︎
Return the seconds since the file(path) was last modified
Source code in libs/shellfish/shellfish/fs/__init__.py
378 379 380 |
|
shellfish.fs.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]]
⚓︎
Return a files_gen() and a dirs_gen() in one swell-foop
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath is a directory |
True
|
Returns:
Type | Description |
---|---|
Tuple[Iterator[str], Iterator[str]]
|
A tuple of two generators (files_gen(), dirs_gen()) |
Examples:
>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2a']
>>> _files, _dirs = files_dirs_gen(tmpdir)
>>> _files = list(_files)
>>> _dirs = list(_dirs)
>>> files_n_dirs_list = list(sorted(set(_files + _dirs)))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
shellfish.fs.files_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield file-paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields file-paths (absolute or relative) |
Examples:
>>> tmpdir = 'files_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt',
'files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt']
>>> files_list = list(sorted(set(files_gen(tmpdir))))
>>> files_list = [el.replace('\\', '/') for el in files_list]
>>> pprint(files_list)
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> pprint(list(sorted(set(expected_files))))
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> list(sorted(set(files_list))) == list(sorted(set(expected_files)))
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
shellfish.fs.filesize(fspath: FsPath) -> int
⚓︎
Return the size of the given file(path) in bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath as a string or pathlib.Path object |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
size of the fspath in bytes |
Source code in libs/shellfish/shellfish/fs/__init__.py
163 164 165 166 167 168 169 170 171 172 173 |
|
shellfish.fs.filesize_async(fspath: FsPath) -> int
async
⚓︎
Return the size of the file at the given fspath
Examples:
>>> from asyncio import run as aiorun
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmpdir:
... tmpdir = Path(tmpdir)
... fpath = tmpdir / "test.txt"
... written = fpath.write_text("hello world")
... aiorun(filesize_async(fpath))
11
Source code in libs/shellfish/shellfish/fs/_async.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
shellfish.fs.fspath(fspath: FsPath) -> str
⚓︎
Alias for os._fspath; returns fspath string for any type of path
Source code in libs/shellfish/shellfish/fs/__init__.py
93 94 95 |
|
shellfish.fs.glob(pattern: str, *, recursive: bool = False, r: bool = False) -> Iterator[str]
⚓︎
Return an iterator of fspaths matching the given glob pattern
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
Glob pattern |
required |
recursive
|
bool
|
Recursively search directories if True |
False
|
r
|
bool
|
Recursively search directories if True (Alias for recursive) |
False
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Iterator[str]: Iterator of fspaths matching the glob pattern |
Source code in libs/shellfish/shellfish/fs/__init__.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
|
shellfish.fs.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish.fs.is_dir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.fs.is_file(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
133 134 135 |
|
shellfish.fs.is_file_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.fs.is_link(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; alias for islink
Source code in libs/shellfish/shellfish/fs/__init__.py
138 139 140 |
|
shellfish.fs.is_link_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.fs.isdir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
103 104 105 |
|
shellfish.fs.isdir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.fs.isfile(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
98 99 100 |
|
shellfish.fs.isfile_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.fs.islink(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
108 109 110 |
|
shellfish.fs.islink_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.fs.listdir_async(fspath: FsPath) -> List[str]
async
⚓︎
Async version of os.listdir
Source code in libs/shellfish/shellfish/fs/_async.py
133 134 135 |
|
shellfish.fs.listdir_gen(fspath: FsPath = '.', *, abspath: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = False, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[Path]
⚓︎
Return an iterator of strings from DirEntries
Examples >>> tmpdir = 'listdir_gen.doctest' >>> from shellfish import sh >>> from os import makedirs, path, chdir >>> from shutil import rmtree >>> _makedirs(tmpdir, exist_ok=True) >>> pwd = sh.pwd() >>> sh.cd(tmpdir) >>> filepath_parts = [ ... ("dir", "file1.txt"), ... ("dir", "file2.txt"), ... ("dir", "file3.txt"), ... ("dir", "data1.json"), ... ("dir", "dir2", "file1.txt"), ... ("dir", "dir2", "file2.txt"), ... ("dir", "dir2", "file3.txt"), ... ("dir", "dir2a", "file1.txt"), ... ("dir", "dir2a", "file2.txt"), ... ("dir", "dir2a", "file3.txt"), ... ] >>> from shellfish.fs import touch >>> expected_files = [] >>> for f in filepath_parts: ... fspath = path.join(*f) ... fspath = path.join(tmpdir, fspath) ... dirpath = path.dirname(fspath) ... expected_files.append(fspath) ... _makedirs(dirpath, exist_ok=True) ... touch(fspath) >>> dirpath = path.join(tmpdir, 'dir') >>> dirpath.replace("\", "/") 'listdir_gen.doctest/dir' >>> sorted(listdir_gen(dirpath, dirs=False, symlinks=False)) ['data1.json', 'file1.txt', 'file2.txt', 'file3.txt'] >>> abspaths = sorted(listdir_gen(dirpath, abspath=True, dirs=False, symlinks=False)) >>> for abspath in [p.replace("\", "/") for p in abspaths]: ... print(abspath) listdir_gen.doctest/dir/data1.json listdir_gen.doctest/dir/file1.txt listdir_gen.doctest/dir/file2.txt listdir_gen.doctest/dir/file3.txt >>> sh.cd(pwd) >>> import os >>> if path.exists(tmpdir): ... rmtree(tmpdir) >>> path.isdir(tmpdir) False
Source code in libs/shellfish/shellfish/fs/__init__.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
shellfish.fs.lstat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.fs.mkdir(fspath: FsPath, *, parents: bool = False, p: bool = False, exist_ok: bool = False) -> None
⚓︎
Make directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to create |
required |
parents
|
bool
|
Make parent dirs if True; do not make parent dirs if False |
False
|
p
|
bool
|
Make parent dirs if True; do not make parent dirs if False (alias of parents) |
False
|
exist_ok
|
bool
|
Throw error if directory exists and exist_ok is False |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
|
shellfish.fs.mkdirp(fspath: FsPath) -> None
⚓︎
Make directory and parents
Source code in libs/shellfish/shellfish/fs/__init__.py
1435 1436 1437 |
|
shellfish.fs.move(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 |
|
shellfish.fs.path_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 |
|
shellfish.fs.rbytes(filepath: FsPath) -> bytes
⚓︎
Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "rbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> wbytes(fspath, bites_to_save)
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
shellfish.fs.rbytes_async(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.fs.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> Iterable[bytes]
⚓︎
Yield bytes from a given fspath
Source code in libs/shellfish/shellfish/fs/__init__.py
1061 1062 1063 1064 1065 1066 1067 1068 |
|
shellfish.fs.rbytes_gen_async(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.fs.rjson(filepath: FsPath) -> Any
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
|
shellfish.fs.rjson_async(filepath: FsPath) -> Any
async
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
shellfish.fs.rm(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False, verbose: bool = False) -> Union[List[str], None]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): ignore errors and missing files/dirs; default is False
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 |
|
shellfish.fs.rm_gen(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False) -> Generator[str, Any, Any]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): Force removal of files and directories
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
shellfish.fs.rmdir(fspath: FsPath, *, force: bool = False, recursive: bool = False) -> None
⚓︎
Remove directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to remove |
required |
force
|
bool
|
Force removal of files and directories |
False
|
recursive
|
bool
|
Recursively remove all contents if True |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
shellfish.fs.rmfile(fspath: FsPath, *, dryrun: bool = False) -> str
⚓︎
Remove a file at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath to remove |
required |
dryrun
|
bool
|
Do not remove file if True |
False
|
Returns:
Type | Description |
---|---|
str
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
|
shellfish.fs.rstring(filepath: FsPath, *, encoding: str = 'utf-8') -> str
⚓︎
Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
Encoding to use for reading the file |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "lstring.doctest.txt"
>>> sstring(fspath, r'Check out this string')
21
>>> lstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
|
shellfish.fs.rstring_async(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.fs.safepath(fspath: FsPath) -> str
⚓︎
Check if a file/dir path is save/unused; returns an unused path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
file-system path; file or directory path string or Path obj |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
file/dir path that does not exist and contains the given path |
Source code in libs/shellfish/shellfish/fs/__init__.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
shellfish.fs.scandir(dirpath: FsPath = '.') -> Iterable[DirEntry[AnyStr]]
⚓︎
Typed version of os.scandir
Source code in libs/shellfish/shellfish/fs/__init__.py
176 177 178 179 180 |
|
shellfish.fs.scandir_gen(fspath: FsPath = '.', *, recursive: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = True, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[DirEntry[str]]
⚓︎
Return an iterator of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
(FsPath): dirpath to look through |
'.'
|
recursive
|
bool
|
recursively scan the directory |
False
|
follow_symlinks
|
bool
|
follow symlinks when checking for dirs and files |
True
|
files
|
bool
|
include files |
True
|
dirs
|
bool
|
include directories |
True
|
symlinks
|
bool
|
include symlinks |
True
|
dirs_only
|
bool
|
only include directories |
False
|
files_only
|
bool
|
only include files |
False
|
symlinks_only
|
bool
|
only include symlinks |
False
|
Returns:
Type | Description |
---|---|
Iterator[DirEntry[str]]
|
Iterator[DirEntry]: Iterator of os.DirEntry objects |
Raises:
Type | Description |
---|---|
ValueError
|
if any of the kwargs ( |
Source code in libs/shellfish/shellfish/fs/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.fs.scandir_list(dirpath: FsPath = '.') -> List[DirEntry[AnyStr]]
⚓︎
Return a list of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Dirpath to scan |
'.'
|
Returns:
Type | Description |
---|---|
List[DirEntry[AnyStr]]
|
List[DirEntry]: List of os.DirEntry objects |
Source code in libs/shellfish/shellfish/fs/__init__.py
183 184 185 186 187 188 189 190 191 192 193 |
|
shellfish.fs.sep_join(path_strings: Iterator[str]) -> str
⚓︎
Join iterable of strings on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1319 1320 1321 |
|
shellfish.fs.sep_lstrip(fspath: FsPath) -> str
⚓︎
Left-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1329 1330 1331 |
|
shellfish.fs.sep_rstrip(fspath: FsPath) -> str
⚓︎
Right-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1334 1335 1336 |
|
shellfish.fs.sep_split(fspath: FsPath) -> Tuple[str, ...]
⚓︎
Split a string on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1314 1315 1316 |
|
shellfish.fs.sep_strip(fspath: FsPath) -> str
⚓︎
Strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1324 1325 1326 |
|
shellfish.fs.shebang(fspath: FsPath) -> Union[None, str]
⚓︎
Get the shebang string given a fspath; Returns None if no shebang
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file that might have a shebang |
required |
Returns:
Type | Description |
---|---|
Union[None, str]
|
Optional[str]: The shebang string if it exists, None otherwise |
Examples:
>>> from inspect import getabsfile
>>> script = 'ashellscript.sh'
>>> with open(script, 'w') as f:
... f.write('#!/bin/bash\necho "howdy"\n')
25
>>> shebang(script)
'#!/bin/bash'
>>> from os import remove
>>> remove(script)
Source code in libs/shellfish/shellfish/fs/__init__.py
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
|
shellfish.fs.stat(fspath: FsPath) -> os_stat_result
⚓︎
Return the os.stat_result object for a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory |
required |
Returns:
Type | Description |
---|---|
stat_result
|
os.stat_result: stat_result object |
Source code in libs/shellfish/shellfish/fs/__init__.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 |
|
shellfish.fs.stat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.fs.touch(fspath: FsPath, *, mkdirp: bool = True) -> None
⚓︎
Create an empty file given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path for where to make an empty file |
required |
mkdirp
|
bool
|
Make parent directories if they don't exist |
True
|
Source code in libs/shellfish/shellfish/fs/__init__.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
shellfish.fs.walk_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield all paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'walk_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f).replace('\\', '/')
... fspath = path.join(tmpdir, fspath).replace('\\', '/')
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = [el.replace('\\', '/') for el in sorted(set(expected_dirs))]
>>> from pprint import pprint
>>> pprint(expected_files)
['walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt']
>>> pprint(expected_dirs)
['walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2a']
>>> walk_gen_list = list(sorted(walk_gen(tmpdir)))
>>> walk_gen_list = [el.replace('\\', '/') for el in walk_gen_list]
>>> pprint(walk_gen_list)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> pprint(expected)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> walk_gen_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
shellfish.fs.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> wbytes(fspath, bites_to_save)
20
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 |
|
shellfish.fs.wbytes_async(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.fs.wbytes_gen(filepath: FsPath, bytes_gen: Iterable[bytes], append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Iterable[bytes]
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes_gen.doctest.txt"
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save # they are bytes!
(b'These are some bytes... ', b'more bytes!')
>>> wbytes_gen(fspath, (b for b in bites_to_save))
35
>>> rbytes(fspath)
b'These are some bytes... more bytes!'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
shellfish.fs.wbytes_gen_async(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.fs.wjson(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, chmod: Optional[int] = None, append: bool = False, **kwargs: Any) -> int
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Append a newline to the end of the file |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
append
|
bool
|
Append to the file if True, overwrite otherwise; default |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dumpb |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 |
|
shellfish.fs.wjson_async(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, append: bool = False, chmod: Optional[int] = None, **kwargs: Any) -> int
async
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dump |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "wjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "wjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
shellfish.fs.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
String encoding to write file with |
'utf-8'
|
append
|
bool
|
Flag to append to file; default = False |
False
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "sstring.doctest.txt"
>>> wstring(fspath, r'Check out this string')
21
>>> rstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
shellfish.fs.wstring_async(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
Modules⚓︎
shellfish.fs.promises
⚓︎
shellfish.fs.promises
Functions⚓︎
shellfish.fs.promises.dir_exists(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.fs.promises.file_exists(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.fs.promises.is_dir(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.fs.promises.is_file(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.fs.promises.is_link(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.fs.promises.isdir(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.fs.promises.isfile(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.fs.promises.islink(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.fs.promises.lstat(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.fs.promises.rbytes(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.fs.promises.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.fs.promises.rstring(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.fs.promises.stat(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.fs.promises.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.fs.promises.wbytes_gen(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.fs.promises.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
shellfish.sh
⚓︎
shell utils
Classes⚓︎
shellfish.sh.Done(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
PRun => 'ProcessRun' for finished processes
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
Attributes⚓︎
shellfish.sh.Done.__property_fields__: Set[str]
property
⚓︎
Returns a set of property names for the class that have a setter
Functions⚓︎
shellfish.sh.Done.__contains__(key: _KT) -> bool
⚓︎
Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.sh.Done.__ge__(filepath: FsPath) -> 'Done'
⚓︎
Operator overload for writing stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
659 660 661 662 663 664 665 666 667 668 669 670 |
|
shellfish.sh.Done.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎
Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.sh.Done.__getattr__(item: _KT) -> Any
⚓︎
Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.sh.Done.__gt__(filepath: FsPath) -> None
⚓︎
Operator overload for writing a stdout to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
650 651 652 653 654 655 656 657 |
|
shellfish.sh.Done.__irshift__(filepath: FsPath) -> 'Done'
⚓︎
Operator overload for appending stderr to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
Returns:
Type | Description |
---|---|
'Done'
|
Done object; self |
Source code in libs/shellfish/shellfish/sh.py
681 682 683 684 685 686 687 688 689 690 691 692 |
|
shellfish.sh.Done.__post_init__() -> None
⚓︎
Write the stdout/stdout to sys.stdout/sys.stderr post object init
Source code in libs/shellfish/shellfish/sh.py
538 539 540 541 |
|
shellfish.sh.Done.__rshift__(filepath: FsPath) -> None
⚓︎
Operator overload for appending stdout to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
Source code in libs/shellfish/shellfish/sh.py
672 673 674 675 676 677 678 679 |
|
shellfish.sh.Done.__setitem__(key: _KT, value: _VT) -> None
⚓︎
Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.sh.Done.asdict() -> Dict[_KT, Any]
⚓︎
Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.sh.Done.check(ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0) -> None
⚓︎
Check returncode and stderr
Raises:
Type | Description |
---|---|
DoneError
|
If return code is non-zero and stderr is not None |
Source code in libs/shellfish/shellfish/sh.py
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
|
shellfish.sh.Done.completed_process() -> CompletedProcess[str]
⚓︎
Return subprocess.CompletedProcess object
Source code in libs/shellfish/shellfish/sh.py
631 632 633 634 635 636 637 638 |
|
shellfish.sh.Done.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎
Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.sh.Done.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎
Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.sh.Done.done_dict() -> DoneDict
⚓︎
Return Done object as typed-dict
Source code in libs/shellfish/shellfish/sh.py
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
|
shellfish.sh.Done.done_obj() -> DoneObj
⚓︎
Return Done object typed dict
Source code in libs/shellfish/shellfish/sh.py
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
|
shellfish.sh.Done.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎
Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.sh.Done.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎
Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.sh.Done.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.sh.Done.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎
Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.sh.Done.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎
Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.sh.Done.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.sh.Done.eject() -> Dict[_KT, _VT]
⚓︎
Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.sh.Done.entries() -> ItemsView[_KT, _VT]
⚓︎
Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.sh.Done.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.sh.Done.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.sh.Done.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.sh.Done.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎
Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.sh.Done.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.sh.Done.grep(string: str) -> List[str]
⚓︎
Return lines in stdout that have
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
String to search for |
required |
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of strings of stdout lines containing the given search string |
Source code in libs/shellfish/shellfish/sh.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 |
|
shellfish.sh.Done.has_required_fields() -> bool
classmethod
⚓︎
Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.sh.Done.is_default() -> bool
⚓︎
Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.sh.Done.items() -> ItemsView[_KT, _VT]
⚓︎
Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.sh.Done.json(*args: Any, **kwargs: Any) -> str
⚓︎
Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.sh.Done.json_parse(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
706 707 708 709 710 711 712 713 714 715 716 717 718 |
|
shellfish.sh.Done.json_parse_stderr(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stderr
Source code in libs/shellfish/shellfish/sh.py
700 701 702 703 704 |
|
shellfish.sh.Done.json_parse_stdout(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout
Source code in libs/shellfish/shellfish/sh.py
694 695 696 697 698 |
|
shellfish.sh.Done.keys() -> KeysView[_KT]
⚓︎
Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.sh.Done.parse_json(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any
⚓︎
Return json parsed stdout (alias bc I keep flip-flopping the fn name)
Source code in libs/shellfish/shellfish/sh.py
720 721 722 723 724 725 726 727 728 |
|
shellfish.sh.Done.recurse() -> None
⚓︎
Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.sh.Done.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.sh.Done.sys_print() -> None
⚓︎
Write self.stdout to sys.stdout and self.stderr to sys.stderr
Source code in libs/shellfish/shellfish/sh.py
616 617 618 619 |
|
shellfish.sh.Done.to_dict() -> Dict[str, Any]
⚓︎
Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.sh.Done.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.sh.Done.to_dict_filter_none() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.sh.Done.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.sh.Done.to_json_dict() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.sh.Done.to_json_obj() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.sh.Done.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.sh.Done.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.sh.Done.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎
Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.sh.Done.write_stderr(filepath: FsPath, *, append: bool = False) -> None
⚓︎
Write stderr as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath of location to write stderr |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
640 641 642 643 644 645 646 647 648 |
|
shellfish.sh.Done.write_stdout(filepath: FsPath, *, append: bool = False) -> None
⚓︎
Write stdout as a string to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to write stdout to |
required |
append
|
bool
|
Flag to append to file or plain write to file |
False
|
Source code in libs/shellfish/shellfish/sh.py
621 622 623 624 625 626 627 628 629 |
|
shellfish.sh.DoneError(done: Done)
⚓︎
Bases: SubprocessError
Raised when run() is called with check=True and the process returns a non-zero exit status.
Attributes:
Name | Type | Description |
---|---|---|
cmd |
str
|
command that was run |
returncode |
int
|
exit status of the process |
stdout |
str
|
standard output (stdout) of the process |
stderr |
str
|
standard error (stderr) of the process |
Source code in libs/shellfish/shellfish/sh.py
462 463 464 465 466 467 468 |
|
shellfish.sh.DoneObj
⚓︎
Bases: TypedDict
Todo
deprecate this in favor of DoneDict
shellfish.sh.Flag
⚓︎
Flag obj
Examples:
>>> Flag.__help
'--help'
>>> Flag._v
'-v'
shellfish.sh.FlagMeta
⚓︎
Bases: type
Meta class
Functions⚓︎
shellfish.sh.FlagMeta.attr2flag(string: str) -> str
cached
staticmethod
⚓︎
Convert and return attr to string
Source code in libs/shellfish/shellfish/sh.py
355 356 357 358 359 |
|
shellfish.sh.HrTime(*args: Any, **kwargs: _VT)
⚓︎
Bases: JsonBaseModel
High resolution time
Source code in libs/jsonbourne/jsonbourne/core.py
242 243 244 245 246 247 248 249 250 251 252 253 254 |
|
Attributes⚓︎
shellfish.sh.HrTime.__property_fields__: Set[str]
property
⚓︎
Returns a set of property names for the class that have a setter
Functions⚓︎
shellfish.sh.HrTime.__contains__(key: _KT) -> bool
⚓︎
Check if a key or dot-key is contained within the JsonObj object
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
root level key or a dot-key |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key/dot-key is in the JsonObj; False otherwise |
Examples:
>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
shellfish.sh.HrTime.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]]
classmethod
⚓︎
Return the JsonObj validator functions
Source code in libs/jsonbourne/jsonbourne/core.py
1069 1070 1071 1072 1073 1074 |
|
shellfish.sh.HrTime.__getattr__(item: _KT) -> Any
⚓︎
Return an attr
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
|
shellfish.sh.HrTime.__post_init__() -> Any
⚓︎
Function place holder that is called after object initialization
Source code in libs/jsonbourne/jsonbourne/pydantic.py
98 99 |
|
shellfish.sh.HrTime.__setitem__(key: _KT, value: _VT) -> None
⚓︎
Set JsonObj item with 'key' to 'value'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
_KT
|
Key/item to set |
required |
value
|
_VT
|
Value to set |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Raises:
Type | Description |
---|---|
ValueError
|
If given a key that is not a valid python keyword/identifier |
Examples:
>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
shellfish.sh.HrTime.asdict() -> Dict[_KT, Any]
⚓︎
Return the JsonObj object (and children) as a python dictionary
Source code in libs/jsonbourne/jsonbourne/core.py
894 895 896 |
|
shellfish.sh.HrTime.defaults_dict() -> Dict[str, Any]
classmethod
⚓︎
Return a dictionary of non-required keys -> default value(s)
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary of non-required keys -> default value |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
shellfish.sh.HrTime.dict(*args: Any, **kwargs: Any) -> Dict[str, Any]
⚓︎
Alias for model_dump
Source code in libs/jsonbourne/jsonbourne/pydantic.py
118 119 120 |
|
shellfish.sh.HrTime.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]]
⚓︎
Yield tuples of the form (dot-key, value)
OG-version
def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())
Readable-version
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value
Source code in libs/jsonbourne/jsonbourne/core.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
|
shellfish.sh.HrTime.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]
⚓︎
Return list of tuples of the form (dot-key, value)
Source code in libs/jsonbourne/jsonbourne/core.py
763 764 765 |
|
shellfish.sh.HrTime.dot_keys() -> Iterable[Tuple[str, ...]]
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
Type | Description |
---|---|
Iterable[Tuple[str, ...]]
|
Iterable[str]: List of the dot-notation friendly keys |
The Non-chain version (shown below) is very slightly slower than the
itertools.chain
version.
NON-CHAIN VERSION:
for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k
Source code in libs/jsonbourne/jsonbourne/core.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 |
|
shellfish.sh.HrTime.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]]
⚓︎
Return a list of the JsonObj's dot-notation friendly keys
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sort_keys
|
bool
|
Flag to have the dot-keys be returned sorted |
False
|
Returns:
Type | Description |
---|---|
List[Tuple[str, ...]]
|
List[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
660 661 662 663 664 665 666 667 668 669 670 671 672 |
|
shellfish.sh.HrTime.dot_keys_set() -> Set[Tuple[str, ...]]
⚓︎
Return a set of the JsonObj's dot-notation friendly keys
Returns:
Type | Description |
---|---|
Set[Tuple[str, ...]]
|
Set[str]: List of the dot-notation friendly keys |
Source code in libs/jsonbourne/jsonbourne/core.py
674 675 676 677 678 679 680 681 |
|
shellfish.sh.HrTime.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
dot-notation key to look up ('key1.key2.third_key') |
required |
Returns:
Type | Description |
---|---|
Any
|
The result of the dot-notation key look up |
Raises:
Type | Description |
---|---|
KeyError
|
Raised if the dot-key is not in in the object |
ValueError
|
Raised if key is not a str/Tuple[str, ...]/List[str] |
Source code in libs/jsonbourne/jsonbourne/core.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
shellfish.sh.HrTime.eject() -> Dict[_KT, _VT]
⚓︎
Eject to python-builtin dictionary object
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 |
|
shellfish.sh.HrTime.entries() -> ItemsView[_KT, _VT]
⚓︎
Alias for items
Source code in libs/jsonbourne/jsonbourne/core.py
434 435 436 |
|
shellfish.sh.HrTime.filter_false(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recurse into sub JsonObjs and dictionaries |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
shellfish.sh.HrTime.filter_none(recursive: bool = False) -> JsonObj[_VT]
⚓︎
Filter key-values where the value is None
but not false-y
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recursive
|
bool
|
Recursively filter out None values |
False
|
Returns:
Type | Description |
---|---|
JsonObj[_VT]
|
JsonObj that has been filtered of None values |
Examples:
>>> d = {
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... 'a': None,
... 'b': 2,
... 'c': {
... 'd': 'herm',
... 'e': None,
... 'falsey_dict': {},
... 'falsey_list': [],
... 'falsey_string': '',
... 'is_false': False,
... },
... }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
'a': None,
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'e': None,
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
'b': 2,
'c': {'d': 'herm',
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False},
'falsey_dict': {},
'falsey_list': [],
'falsey_string': '',
'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
shellfish.sh.HrTime.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a dictionary of data
Source code in libs/jsonbourne/jsonbourne/core.py
898 899 900 901 |
|
shellfish.sh.HrTime.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT
classmethod
⚓︎
Create class from dict filtering keys not in (sub)class' fields
Source code in libs/jsonbourne/jsonbourne/pydantic.py
278 279 280 281 282 283 284 |
|
shellfish.sh.HrTime.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]
classmethod
⚓︎
Return a JsonObj object from a json string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_string
|
str
|
JSON string to convert to a JsonObj |
required |
Returns:
Name | Type | Description |
---|---|---|
JsonObjT |
JsonObj[_VT]
|
JsonObj object for the given JSON string |
Source code in libs/jsonbourne/jsonbourne/core.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
|
shellfish.sh.HrTime.from_seconds(seconds: float) -> 'HrTime'
classmethod
⚓︎
Return HrTime object from seconds
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
'HrTime'
|
HrTime object |
Source code in libs/shellfish/shellfish/sh.py
417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
shellfish.sh.HrTime.has_required_fields() -> bool
classmethod
⚓︎
Return True/False if the (sub)class has any fields that are required
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if any fields for a (sub)class are required |
Source code in libs/jsonbourne/jsonbourne/pydantic.py
286 287 288 289 290 291 292 293 294 |
|
shellfish.sh.HrTime.is_default() -> bool
⚓︎
Check if the object is equal to the default value for its fields
Returns:
Type | Description |
---|---|
bool
|
True if object is equal to the default value for all fields; False otherwise |
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
shellfish.sh.HrTime.items() -> ItemsView[_KT, _VT]
⚓︎
Return an items view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
430 431 432 |
|
shellfish.sh.HrTime.json(*args: Any, **kwargs: Any) -> str
⚓︎
Alias for model_dumps
Source code in libs/jsonbourne/jsonbourne/pydantic.py
122 123 124 |
|
shellfish.sh.HrTime.keys() -> KeysView[_KT]
⚓︎
Return the keys view of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
438 439 440 |
|
shellfish.sh.HrTime.recurse() -> None
⚓︎
Recursively convert all sub dictionaries to JsonObj objects
Source code in libs/jsonbourne/jsonbourne/core.py
256 257 258 |
|
shellfish.sh.HrTime.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
shellfish.sh.HrTime.to_dict() -> Dict[str, Any]
⚓︎
Eject and return object as plain jane dictionary
Source code in libs/jsonbourne/jsonbourne/pydantic.py
255 256 257 |
|
shellfish.sh.HrTime.to_dict_filter_defaults() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
shellfish.sh.HrTime.to_dict_filter_none() -> Dict[str, Any]
⚓︎
Eject object and filter key-values equal to (sub)class' default
Examples:
>>> from typing import Optional
>>> class Thing(JsonBaseModel):
... a: int = 1
... b: str = "herm"
... c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
shellfish.sh.HrTime.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str
⚓︎
Return JSON string of the JsonObj object (and children)
Args:
fmt (bool): If True, return a JSON string with newlines and indentation
pretty (bool): If True, return a JSON string with newlines and indentation
sort_keys (bool): Sort dictionary keys if True
append_newline (bool): Append a newline '
' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps
Returns:
str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 |
|
shellfish.sh.HrTime.to_json_dict() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
shellfish.sh.HrTime.to_json_obj() -> JsonObj[Any]
⚓︎
Eject object and sub-objects to jsonbourne.JsonObj
Examples:
>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
|
shellfish.sh.HrTime.to_json_obj_filter_defaults() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values equal to (sub)class' default
Source code in libs/jsonbourne/jsonbourne/pydantic.py
210 211 212 |
|
shellfish.sh.HrTime.to_json_obj_filter_none() -> JsonObj[Any]
⚓︎
Eject to JsonObj and filter key-values where the value is None
Source code in libs/jsonbourne/jsonbourne/pydantic.py
214 215 216 |
|
shellfish.sh.HrTime.validate_type(val: Any) -> JsonObj[_VT]
classmethod
⚓︎
Validate and convert a value to a JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
1064 1065 1066 1067 |
|
shellfish.sh.HrTimeDict
⚓︎
Bases: TypedDict
High resolution time
shellfish.sh.HrTimeObj
⚓︎
Bases: TypedDict
Todo
deprecate this in favor of HrTimeDict
shellfish.sh.LIN
⚓︎
Bases: LIN
Linux (and Mac) shell commands/methods container
Functions⚓︎
shellfish.sh.LIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
str
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
shellfish.sh.LIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
Allow link to exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
shellfish.sh.LIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
Allow links to already exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
|
shellfish.sh.LIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exist_ok
|
bool
|
Allow links to already exist |
False
|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
Source code in libs/shellfish/shellfish/osfs.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
shellfish.sh.LIN.rsync(src: str, dest: str, delete: bool = False, mkdirs: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> Done
staticmethod
⚓︎
Run an rsync
subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mkdirs
|
bool
|
Make destination directories if they do not already exist; defaults to False. |
False
|
src
|
str
|
Source directory path |
required |
dest
|
str
|
Destination directory path |
required |
delete
|
bool
|
Delete files/directories in destination if they do exist in source |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Name | Type | Description |
---|---|---|
Done |
Done
|
Done object containing the info for the rsync run |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 |
|
shellfish.sh.LIN.rsync_args(src: str, dest: str, delete: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> List[str]
staticmethod
⚓︎
Return args for rsync command on linux/mac
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to remote (raid) tdir |
required |
dest
|
str
|
path to local tdir |
required |
delete
|
bool
|
Flag that will do a 'hard sync' |
False
|
exclude
|
Optional[IterableStr]
|
Strings/patterns to exclude |
None
|
include
|
Optional[IterableStr]
|
Strings/patterns to include |
None
|
dry_run
|
bool
|
Perform operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from rsync |
Rsync return codes::
- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested action not supported: an attempt was made to
manipulate 64-bit files on a platform that cannot support them;
or an option was specified that is supported by the client and
not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/shellfish/sh.py
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 |
|
shellfish.sh.LIN.unlink_dir(link: str) -> None
staticmethod
⚓︎
Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
133 134 135 136 137 138 139 140 141 |
|
shellfish.sh.LIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
143 144 145 146 147 148 149 150 151 152 |
|
shellfish.sh.LIN.unlink_file(link: str) -> None
staticmethod
⚓︎
Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
154 155 156 157 158 159 160 161 162 |
|
shellfish.sh.LIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
164 165 166 167 168 169 170 171 172 173 |
|
shellfish.sh.Stdio
⚓︎
Bases: IntEnum
Standard-io enum object
shellfish.sh.WIN
⚓︎
Bases: WIN
Windows shell commands/methods container
Functions⚓︎
shellfish.sh.WIN.link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a directory symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
shellfish.sh.WIN.link_dirs(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple directory symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, do not raise an exception if the link(s) exist |
False
|
Source code in libs/shellfish/shellfish/osfs.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
shellfish.sh.WIN.link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make a file symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
linkpath
|
str
|
Path to the link to be made |
required |
targetpath
|
str
|
Path to the target of the link to be made |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
shellfish.sh.WIN.link_files(link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False) -> None
staticmethod
⚓︎
Make multiple file symlinks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link_target_tuples
|
List[Tuple[str, str]]
|
Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target. |
required |
exist_ok
|
bool
|
If True, don't raise an exception if the link exists |
False
|
Source code in libs/shellfish/shellfish/osfs.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
shellfish.sh.WIN.robocopy(src: str, dest: str, *, mkdirs: bool = True, delete: bool = False, exclude_files: Optional[Iterable[str]] = None, exclude_dirs: Optional[Iterable[str]] = None, dry_run: bool = False) -> Done
staticmethod
⚓︎
Robocopy wrapper function (crude in that it opens a subprocess)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[Iterable[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
mkdirs
|
bool
|
Flag to make destinaation directories if they do not already exist |
True
|
Returns:
Type | Description |
---|---|
Done
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 |
|
shellfish.sh.WIN.robocopy_args(src: str, dest: str, *, delete: bool = False, exclude_files: Optional[List[str]] = None, exclude_dirs: Optional[List[str]] = None, dry_run: bool = False) -> List[str]
staticmethod
⚓︎
Return list of robocopy command args
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
path to source directory |
required |
dest
|
str
|
path to destination directory |
required |
delete
|
bool
|
Delete files in the destination directory if they do not exist in the source directory |
False
|
exclude_files
|
Optional[List[str]]
|
Strings/patterns with which to exclude files |
None
|
exclude_dirs
|
Optional[List[str]]
|
Strings/patterns with which to exclude directories |
None
|
dry_run
|
bool
|
Do the operation as a dry run |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
subprocess return code from robocopy |
Robocopy return codes::
0. No files were copied. No failure was encountered. No files were
mismatched. The files already exist in the destination
directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
that are not present in the source directory. No files were
copied.
3. Some files were copied. Additional files were present. No
failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
was encountered.
6. Additional files and mismatched files exist. No files were
copied and no failures were encountered. This means that the
files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
files were present.
8. Several files did not copy.
Source code in libs/shellfish/shellfish/sh.py
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 |
|
shellfish.sh.WIN.unlink_dir(link: str) -> None
staticmethod
⚓︎
Unlink a directory symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
269 270 271 272 273 274 275 276 277 278 279 280 |
|
shellfish.sh.WIN.unlink_dirs(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.sh.WIN.unlink_file(link: str) -> None
staticmethod
⚓︎
Unlink a file symlink given a path to the symlink
Parameters:
Name | Type | Description | Default |
---|---|---|---|
link
|
str
|
path to the symlink |
required |
Source code in libs/shellfish/shellfish/osfs.py
298 299 300 301 302 303 304 305 306 307 308 309 |
|
shellfish.sh.WIN.unlink_files(links: IterableStr) -> None
staticmethod
⚓︎
Unlink directory symlinks given the paths the links
Parameters:
Name | Type | Description | Default |
---|---|---|---|
links
|
IterableStr
|
Iterable of paths to links |
required |
Source code in libs/shellfish/shellfish/osfs.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
|
Functions⚓︎
shellfish.sh.basename(fspath: FsPath) -> str
⚓︎
Return the basename of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 |
|
shellfish.sh.cd(dirpath: FsPath) -> None
⚓︎
Change directory to given dirpath; alias for os.chdir
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory fspath |
required |
Source code in libs/shellfish/shellfish/sh.py
1886 1887 1888 1889 1890 1891 1892 1893 |
|
shellfish.sh.chmod(fspath: FsPath, mode: int) -> None
⚓︎
Change the access permissions of a file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file to chmod |
required |
mode
|
int
|
Permissions mode as an int |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 |
|
shellfish.sh.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str]
⚓︎
Copy a file given a source-path and a destination-path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source fspath |
required |
dest
|
str
|
Destination fspath |
required |
dryrun
|
bool
|
Do not copy file if True just return the src and dest |
False
|
mkdirp
|
bool
|
Create parent directories if they do not exist |
False
|
Source code in libs/shellfish/shellfish/fs/__init__.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
shellfish.sh.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None
⚓︎
Copy the directory/file src to the directory/file dest
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
str
|
Source directory/file to copy |
required |
dest
|
FsPath
|
Destination directory/file to copy |
required |
force
|
bool
|
Force the copy (like -f flag for cp in shell) |
True
|
recursive
|
bool
|
Recursive copy (like -r flag for cp in shell) |
False
|
r
|
bool
|
alias for recursive |
False
|
f
|
bool
|
alias for force |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If src is a directory and recursive and r are both |
Source code in libs/shellfish/shellfish/fs/__init__.py
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 |
|
shellfish.sh.decode_stdio_bytes(stdio_bytes: Union[str, bytes], lf: bool = True) -> str
⚓︎
Return Stdio bytes from stdout/stderr as a string
Args:
stdio_bytes (bytes): STDOUT/STDERR bytes
lf (bool): Replace `
line endings with
`
Returns:
str: decoded stdio bytes
Source code in libs/shellfish/shellfish/sh.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
shellfish.sh.dir_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
123 124 125 |
|
shellfish.sh.dir_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the directory exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
128 129 130 |
|
shellfish.sh.dirname(fspath: FsPath) -> str
⚓︎
Return dirname/parent-dir of given path; alias of os.path.dirname
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
basename of path |
Source code in libs/shellfish/shellfish/sh.py
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 |
|
shellfish.sh.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all dirpaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
|
shellfish.sh.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield directory-paths beneath a dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
'dirs_gen.doctest/dir',
'dirs_gen.doctest/dir/dir2',
'dirs_gen.doctest/dir/dir2/file1.txt',
'dirs_gen.doctest/dir/dir2/file2.txt',
'dirs_gen.doctest/dir/dir2/file3.txt',
'dirs_gen.doctest/dir/dir2a',
'dirs_gen.doctest/dir/dir2a/file1.txt',
'dirs_gen.doctest/dir/dir2a/file2.txt',
'dirs_gen.doctest/dir/dir2a/file3.txt',
'dirs_gen.doctest/dir/file1.txt',
'dirs_gen.doctest/dir/file2.txt',
'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
shellfish.sh.do(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[FsPath] = None, shell: bool = False, check: bool = False, tee: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
tee
|
bool
|
Flag to tee the subprocess stdout and stderr to sys.stdout/stderr |
False
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check against |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
if args and *popenargs are both given |
Source code in libs/shellfish/shellfish/sh.py
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
|
shellfish.sh.do_async(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Raises:
Type | Description |
---|---|
ValueError
|
If both *popenargs and args are given |
Source code in libs/shellfish/shellfish/sh.py
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
|
shellfish.sh.do_asyncify(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess asynchronously using asyncified version of do
Source code in libs/shellfish/shellfish/sh.py
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
shellfish.sh.doa(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
async
⚓︎
Run a subprocess and await its completion
Alias for sh.do_async
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
check
|
bool
|
Check the result returncode |
False
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
cwd
|
Optional[str]
|
Current working directory (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) that are considered OK (Default value = 0) |
0
|
dryrun
|
bool
|
Flag to not run the subprocess but return a Done object |
False
|
extenv
|
bool
|
Extend environment with the current environment (Default value = True) |
True
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 |
|
shellfish.sh.echo(*objects: Any, sep: str = ' ', end: str = '\n', file: Optional[IO[str]] = None, flush: bool = False) -> None
⚓︎
Print/echo function
Args:
*objects: Item(s) to print/echo
sep: Separator to print with
end: End of print suffix; defaults to `
` file: File like object to write to if not stdout flush: Flush the file after writing
Examples:
>>> echo("shellfish")
shellfish
Source code in libs/shellfish/shellfish/echo.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
shellfish.sh.exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
113 114 115 |
|
shellfish.sh.export(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
if unable to parse key/val |
Source code in libs/shellfish/shellfish/sh.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 |
|
shellfish.sh.extension(fspath: str, *, period: bool = False) -> str
⚓︎
Return the extension for a fspath
Examples:
>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/shellfish/fs/__init__.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
|
shellfish.sh.file_exists(fspath: FsPath) -> bool
⚓︎
Return True if the given path exists; False otherwise; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
118 119 120 |
|
shellfish.sh.file_exists_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the file exists; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
123 124 125 |
|
shellfish.sh.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]
⚓︎
Yield lines from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
File to yield lines from |
required |
keepends
|
bool
|
Flag to keep the ends of the file lines |
True
|
Yields:
Type | Description |
---|---|
Iterable[str]
|
Lines from the given fspath |
Examples:
>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
... file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
... file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
shellfish.sh.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool
⚓︎
Compare 2 files for equality given their filepaths
Parameters:
Name | Type | Description | Default |
---|---|---|---|
left
|
FsPath
|
Filepath 1 |
required |
right
|
FsPath
|
Filepath 2 |
required |
shallow
|
bool
|
Check only size and modification time if True |
True
|
blocksize
|
int
|
Chunk size to read files |
65536
|
Returns:
Type | Description |
---|---|
bool
|
True if files are equal, False otherwise |
Source code in libs/shellfish/shellfish/fs/__init__.py
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
shellfish.sh.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
|
shellfish.sh.filepath_mtimedelta_sec(filepath: FsPath) -> float
⚓︎
Return the seconds since the file(path) was last modified
Source code in libs/shellfish/shellfish/fs/__init__.py
378 379 380 |
|
shellfish.sh.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]]
⚓︎
Return a files_gen() and a dirs_gen() in one swell-foop
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath is a directory |
True
|
Returns:
Type | Description |
---|---|
Tuple[Iterator[str], Iterator[str]]
|
A tuple of two generators (files_gen(), dirs_gen()) |
Examples:
>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2a']
>>> _files, _dirs = files_dirs_gen(tmpdir)
>>> _files = list(_files)
>>> _dirs = list(_dirs)
>>> files_n_dirs_list = list(sorted(set(_files + _dirs)))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['files_dirs_gen.doctest',
'files_dirs_gen.doctest/dir',
'files_dirs_gen.doctest/dir/dir2',
'files_dirs_gen.doctest/dir/dir2/file1.txt',
'files_dirs_gen.doctest/dir/dir2/file2.txt',
'files_dirs_gen.doctest/dir/dir2/file3.txt',
'files_dirs_gen.doctest/dir/dir2a',
'files_dirs_gen.doctest/dir/dir2a/file1.txt',
'files_dirs_gen.doctest/dir/dir2a/file2.txt',
'files_dirs_gen.doctest/dir/dir2a/file3.txt',
'files_dirs_gen.doctest/dir/file1.txt',
'files_dirs_gen.doctest/dir/file2.txt',
'files_dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
shellfish.sh.files_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield file-paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check that dir exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields file-paths (absolute or relative) |
Examples:
>>> tmpdir = 'files_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt',
'files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt']
>>> files_list = list(sorted(set(files_gen(tmpdir))))
>>> files_list = [el.replace('\\', '/') for el in files_list]
>>> pprint(files_list)
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> pprint(list(sorted(set(expected_files))))
['files_gen.doctest/dir/dir2/file1.txt',
'files_gen.doctest/dir/dir2/file2.txt',
'files_gen.doctest/dir/dir2/file3.txt',
'files_gen.doctest/dir/dir2a/file1.txt',
'files_gen.doctest/dir/dir2a/file2.txt',
'files_gen.doctest/dir/dir2a/file3.txt',
'files_gen.doctest/dir/file1.txt',
'files_gen.doctest/dir/file2.txt',
'files_gen.doctest/dir/file3.txt']
>>> list(sorted(set(files_list))) == list(sorted(set(expected_files)))
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
shellfish.sh.filesize(fspath: FsPath) -> int
⚓︎
Return the size of the given file(path) in bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath as a string or pathlib.Path object |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
size of the fspath in bytes |
Source code in libs/shellfish/shellfish/fs/__init__.py
163 164 165 166 167 168 169 170 171 172 173 |
|
shellfish.sh.filesize_async(fspath: FsPath) -> int
async
⚓︎
Return the size of the file at the given fspath
Examples:
>>> from asyncio import run as aiorun
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmpdir:
... tmpdir = Path(tmpdir)
... fpath = tmpdir / "test.txt"
... written = fpath.write_text("hello world")
... aiorun(filesize_async(fpath))
11
Source code in libs/shellfish/shellfish/fs/_async.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
shellfish.sh.flatten_args(*args: Union[Any, List[Any]]) -> List[str]
⚓︎
Flatten possibly nested iterables of sequences to a list of strings
Examples:
>>> list(flatten_args("cmd", ["uno", "dos", "tres"]))
['cmd', 'uno', 'dos', 'tres']
>>> list(flatten_args("cmd", ["uno", "dos", "tres", ["4444", "five"]]))
['cmd', 'uno', 'dos', 'tres', '4444', 'five']
Source code in libs/shellfish/shellfish/sh.py
834 835 836 837 838 839 840 841 842 843 844 |
|
shellfish.sh.fspath(fspath: FsPath) -> str
⚓︎
Alias for os._fspath; returns fspath string for any type of path
Source code in libs/shellfish/shellfish/fs/__init__.py
93 94 95 |
|
shellfish.sh.glob(pattern: str, *, recursive: bool = False, r: bool = False) -> Iterator[str]
⚓︎
Return an iterator of fspaths matching the given glob pattern
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
Glob pattern |
required |
recursive
|
bool
|
Recursively search directories if True |
False
|
r
|
bool
|
Recursively search directories if True (Alias for recursive) |
False
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Iterator[str]: Iterator of fspaths matching the glob pattern |
Source code in libs/shellfish/shellfish/fs/__init__.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
|
shellfish.sh.is_dir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; alias for isdir
Source code in libs/shellfish/shellfish/fs/__init__.py
128 129 130 |
|
shellfish.sh.is_dir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
75 76 77 |
|
shellfish.sh.is_file(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; alias for isfile
Source code in libs/shellfish/shellfish/fs/__init__.py
133 134 135 |
|
shellfish.sh.is_file_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
65 66 67 |
|
shellfish.sh.is_link(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; alias for islink
Source code in libs/shellfish/shellfish/fs/__init__.py
138 139 140 |
|
shellfish.sh.is_link_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
85 86 87 |
|
shellfish.sh.isdir(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a directory; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
103 104 105 |
|
shellfish.sh.isdir_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
70 71 72 |
|
shellfish.sh.isfile(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
98 99 100 |
|
shellfish.sh.isfile_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a file; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
60 61 62 |
|
shellfish.sh.islink(fspath: FsPath) -> bool
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/__init__.py
108 109 110 |
|
shellfish.sh.islink_async(fspath: FsPath) -> bool
async
⚓︎
Return True if the given path is a link; False otherwise
Source code in libs/shellfish/shellfish/fs/_async.py
80 81 82 |
|
shellfish.sh.listdir_async(fspath: FsPath) -> List[str]
async
⚓︎
Async version of os.listdir
Source code in libs/shellfish/shellfish/fs/_async.py
133 134 135 |
|
shellfish.sh.listdir_gen(fspath: FsPath = '.', *, abspath: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = False, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[Path]
⚓︎
Return an iterator of strings from DirEntries
Examples >>> tmpdir = 'listdir_gen.doctest' >>> from shellfish import sh >>> from os import makedirs, path, chdir >>> from shutil import rmtree >>> _makedirs(tmpdir, exist_ok=True) >>> pwd = sh.pwd() >>> sh.cd(tmpdir) >>> filepath_parts = [ ... ("dir", "file1.txt"), ... ("dir", "file2.txt"), ... ("dir", "file3.txt"), ... ("dir", "data1.json"), ... ("dir", "dir2", "file1.txt"), ... ("dir", "dir2", "file2.txt"), ... ("dir", "dir2", "file3.txt"), ... ("dir", "dir2a", "file1.txt"), ... ("dir", "dir2a", "file2.txt"), ... ("dir", "dir2a", "file3.txt"), ... ] >>> from shellfish.fs import touch >>> expected_files = [] >>> for f in filepath_parts: ... fspath = path.join(*f) ... fspath = path.join(tmpdir, fspath) ... dirpath = path.dirname(fspath) ... expected_files.append(fspath) ... _makedirs(dirpath, exist_ok=True) ... touch(fspath) >>> dirpath = path.join(tmpdir, 'dir') >>> dirpath.replace("\", "/") 'listdir_gen.doctest/dir' >>> sorted(listdir_gen(dirpath, dirs=False, symlinks=False)) ['data1.json', 'file1.txt', 'file2.txt', 'file3.txt'] >>> abspaths = sorted(listdir_gen(dirpath, abspath=True, dirs=False, symlinks=False)) >>> for abspath in [p.replace("\", "/") for p in abspaths]: ... print(abspath) listdir_gen.doctest/dir/data1.json listdir_gen.doctest/dir/file1.txt listdir_gen.doctest/dir/file2.txt listdir_gen.doctest/dir/file3.txt >>> sh.cd(pwd) >>> import os >>> if path.exists(tmpdir): ... rmtree(tmpdir) >>> path.isdir(tmpdir) False
Source code in libs/shellfish/shellfish/fs/__init__.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
shellfish.sh.ls(dirpath: FsPath = '.', abspath: bool = False) -> List[str]
⚓︎
List files and dirs given a dirpath (defaults to pwd)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
path-string to directory to list |
'.'
|
abspath
|
bool
|
Give absolute paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of the directory items |
Source code in libs/shellfish/shellfish/sh.py
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 |
|
shellfish.sh.ls_async(dirpath: FsPath = '.', abspath: bool = False) -> List[str]
async
⚓︎
List files and dirs given a dirpath (defaults to pwd)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
path-string to directory to list |
'.'
|
abspath
|
bool
|
Give absolute paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of the directory items |
Source code in libs/shellfish/shellfish/sh.py
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 |
|
shellfish.sh.ls_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the directories in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want list directories |
'.'
|
abspath
|
bool
|
Return absolute directory paths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of directories as strings |
Source code in libs/shellfish/shellfish/sh.py
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 |
|
shellfish.sh.ls_files(dirpath: FsPath = '.', *, abspath: bool = False) -> List[str]
⚓︎
List the files in a given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path for which one might want to list files |
'.'
|
abspath
|
bool
|
Return absolute filepaths |
False
|
Returns:
Type | Description |
---|---|
List[str]
|
List of files as strings |
Source code in libs/shellfish/shellfish/sh.py
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 |
|
shellfish.sh.ls_files_dirs(dirpath: FsPath = '.', *, abspath: bool = False) -> Tuple[List[str], List[str]]
⚓︎
List the files and directories given directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to execute on |
'.'
|
abspath
|
bool
|
Return absolute file/directory paths |
False
|
Returns:
Type | Description |
---|---|
Tuple[List[str], List[str]]
|
Two lists of strings; the first is a list of the files and the second is a list of the directories |
Source code in libs/shellfish/shellfish/sh.py
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 |
|
shellfish.sh.lstat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
99 100 101 |
|
shellfish.sh.mkdir(fspath: FsPath, *, parents: bool = False, p: bool = False, exist_ok: bool = False) -> None
⚓︎
Make directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to create |
required |
parents
|
bool
|
Make parent dirs if True; do not make parent dirs if False |
False
|
p
|
bool
|
Make parent dirs if True; do not make parent dirs if False (alias of parents) |
False
|
exist_ok
|
bool
|
Throw error if directory exists and exist_ok is False |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
|
shellfish.sh.mkdirp(fspath: FsPath) -> None
⚓︎
Make directory and parents
Source code in libs/shellfish/shellfish/fs/__init__.py
1435 1436 1437 |
|
shellfish.sh.move(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/fs/__init__.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 |
|
shellfish.sh.mv(src: FsPath, dest: FsPath) -> None
⚓︎
Move file(s) like on the command line
Parameters:
Name | Type | Description | Default |
---|---|---|---|
src
|
FsPath
|
source file(s) |
required |
dest
|
FsPath
|
destination path |
required |
Source code in libs/shellfish/shellfish/sh.py
2211 2212 2213 2214 2215 2216 2217 2218 2219 |
|
shellfish.sh.path_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path]
⚓︎
Yield all filepaths as pathlib.Path objects beneath a dirpath
Source code in libs/shellfish/shellfish/fs/__init__.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 |
|
shellfish.sh.pstderr(proc: CompletedProcess[AnyStr]) -> str
⚓︎
Get the STDERR as a string from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
python subprocess.process object with STDERR |
required |
Returns:
Type | Description |
---|---|
str
|
STDERR for the proc as string |
Source code in libs/shellfish/shellfish/sh.py
790 791 792 793 794 795 796 797 798 799 800 801 802 |
|
shellfish.sh.pstdout(proc: CompletedProcess[AnyStr]) -> str
⚓︎
Get the STDOUT as a string from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
python subprocess.process object with stdout |
required |
Returns:
Type | Description |
---|---|
str
|
STDOUT for the proc as string |
Source code in libs/shellfish/shellfish/sh.py
775 776 777 778 779 780 781 782 783 784 785 786 787 |
|
shellfish.sh.pstdout_pstderr(proc: CompletedProcess[AnyStr]) -> Tuple[str, str]
⚓︎
Get the STDOUT and STDERR as strings from a subprocess
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proc
|
CompletedProcess[AnyStr]
|
Completed-subprocess |
required |
Returns:
Type | Description |
---|---|
Tuple[str, str]
|
Tuple of two strings: (stdout-string, stderr-string) |
Source code in libs/shellfish/shellfish/sh.py
805 806 807 808 809 810 811 812 813 814 815 |
|
shellfish.sh.pwd() -> str
⚓︎
Return present-working-directory path string; alias for os.getcwd
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
present working directory as string |
Examples:
>>> import os
>>> pwd() == os.getcwd()
True
Source code in libs/shellfish/shellfish/sh.py
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 |
|
shellfish.sh.q(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> q("hello world")
"'hello world'"
>>> q("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 |
|
shellfish.sh.quote(string: str) -> str
⚓︎
Typed alias for shlex.quote
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
string to quote |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
quoted string |
Examples:
>>> quote("hello world")
"'hello world'"
>>> quote("hello 'world'")
'\'hello \'"\'"\'world\'"\'"\'\''
Source code in libs/shellfish/shellfish/sh.py
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 |
|
shellfish.sh.rbytes(filepath: FsPath) -> bytes
⚓︎
Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "rbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> wbytes(fspath, bites_to_save)
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
shellfish.sh.rbytes_async(filepath: FsPath) -> bytes
async
⚓︎
(ASYNC) Load/Read bytes from a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath read as bytes |
required |
Returns:
Type | Description |
---|---|
bytes
|
bytes from the fspath |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "rbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
shellfish.sh.rbytes_gen(filepath: FsPath, blocksize: int = 65536) -> Iterable[bytes]
⚓︎
Yield bytes from a given fspath
Source code in libs/shellfish/shellfish/fs/__init__.py
1061 1062 1063 1064 1065 1066 1067 1068 |
|
shellfish.sh.rbytes_gen_async(filepath: FsPath, blocksize: int = 65536) -> AsyncIterable[Union[bytes, str]]
async
⚓︎
Yield (asynchronously) bytes from a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to read from |
required |
blocksize
|
int
|
size of the block to read |
65536
|
Yields:
Type | Description |
---|---|
AsyncIterable[Union[bytes, str]]
|
bytes from AsyncIterable[bytes] of the file bytes |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'rbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
shellfish.sh.rjson(filepath: FsPath) -> Any
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
|
shellfish.sh.rjson_async(filepath: FsPath) -> Any
async
⚓︎
Load/Read-&-parse json data given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath to load/read data from |
required |
Returns:
Type | Description |
---|---|
Any
|
Parsed JSON data |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
shellfish.sh.rm(fspath: FsPath, *, force: bool = False, recursive: bool = False, verbose: bool = False, f: bool = False, r: bool = False, v: bool = False, dryrun: bool = False) -> None
⚓︎
Remove files & directories in the style of the shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory to remove |
required |
force
|
bool
|
Flag to force removal; ignore missing |
False
|
recursive
|
bool
|
Flag to remove recursively (like the |
False
|
verbose
|
bool
|
Flag to be verbose |
False
|
f
|
bool
|
alias for force kwarg |
False
|
v
|
bool
|
alias for verbose |
False
|
r
|
bool
|
alias for recursive kwarg |
False
|
dryrun
|
bool
|
Flag to not actually remove anything |
False
|
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/sh.py
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 |
|
shellfish.sh.rm_gen(fspath: FsPath, *, force: bool = False, recursive: bool = False, dryrun: bool = False) -> Generator[str, Any, Any]
⚓︎
Remove files & directories in the style of the shell
Args:
fspath (FsPath): Path to file or directory to remove
force (bool): Force removal of files and directories
recursive (bool): Flag to remove recursively (like the -r
in rm -r dir
)
dryrun (bool): Do not remove file if True
Raises:
Type | Description |
---|---|
ValueError
|
If recursive and r are |
Source code in libs/shellfish/shellfish/fs/__init__.py
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
shellfish.sh.rmdir(fspath: FsPath, *, force: bool = False, recursive: bool = False) -> None
⚓︎
Remove directory at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Directory path to remove |
required |
force
|
bool
|
Force removal of files and directories |
False
|
recursive
|
bool
|
Recursively remove all contents if True |
False
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
shellfish.sh.rmfile(fspath: FsPath, *, dryrun: bool = False) -> str
⚓︎
Remove a file at given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Filepath to remove |
required |
dryrun
|
bool
|
Do not remove file if True |
False
|
Returns:
Type | Description |
---|---|
str
|
None |
Source code in libs/shellfish/shellfish/fs/__init__.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 |
|
shellfish.sh.rstring(filepath: FsPath, *, encoding: str = 'utf-8') -> str
⚓︎
Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
Encoding to use for reading the file |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "lstring.doctest.txt"
>>> sstring(fspath, r'Check out this string')
21
>>> lstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
|
shellfish.sh.rstring_async(filepath: FsPath, encoding: str = 'utf-8') -> str
async
⚓︎
(ASYNC) Load/Read a string given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Filepath for file to read |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
String read from given fspath |
Source code in libs/shellfish/shellfish/fs/_async.py
407 408 409 410 411 412 413 414 415 416 417 418 |
|
shellfish.sh.safepath(fspath: FsPath) -> str
⚓︎
Check if a file/dir path is save/unused; returns an unused path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
file-system path; file or directory path string or Path obj |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
file/dir path that does not exist and contains the given path |
Source code in libs/shellfish/shellfish/fs/__init__.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
shellfish.sh.scandir(dirpath: FsPath = '.') -> Iterable[DirEntry[AnyStr]]
⚓︎
Typed version of os.scandir
Source code in libs/shellfish/shellfish/fs/__init__.py
176 177 178 179 180 |
|
shellfish.sh.scandir_gen(fspath: FsPath = '.', *, recursive: bool = False, follow_symlinks: bool = True, files: bool = True, dirs: bool = True, symlinks: bool = True, files_only: bool = False, dirs_only: bool = False, symlinks_only: bool = False) -> Iterator[DirEntry[str]]
⚓︎
Return an iterator of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
(FsPath): dirpath to look through |
'.'
|
recursive
|
bool
|
recursively scan the directory |
False
|
follow_symlinks
|
bool
|
follow symlinks when checking for dirs and files |
True
|
files
|
bool
|
include files |
True
|
dirs
|
bool
|
include directories |
True
|
symlinks
|
bool
|
include symlinks |
True
|
dirs_only
|
bool
|
only include directories |
False
|
files_only
|
bool
|
only include files |
False
|
symlinks_only
|
bool
|
only include symlinks |
False
|
Returns:
Type | Description |
---|---|
Iterator[DirEntry[str]]
|
Iterator[DirEntry]: Iterator of os.DirEntry objects |
Raises:
Type | Description |
---|---|
ValueError
|
if any of the kwargs ( |
Source code in libs/shellfish/shellfish/fs/__init__.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
shellfish.sh.scandir_list(dirpath: FsPath = '.') -> List[DirEntry[AnyStr]]
⚓︎
Return a list of os.DirEntry objects
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Dirpath to scan |
'.'
|
Returns:
Type | Description |
---|---|
List[DirEntry[AnyStr]]
|
List[DirEntry]: List of os.DirEntry objects |
Source code in libs/shellfish/shellfish/fs/__init__.py
183 184 185 186 187 188 189 190 191 192 193 |
|
shellfish.sh.seconds2hrtime(seconds: Union[float, int]) -> Tuple[int, int]
⚓︎
Return hr-time Tuple[int, int] (seconds, nanoseconds)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
float
|
number of seconds |
required |
Returns:
Type | Description |
---|---|
Tuple[int, int]
|
Tuple[int, int]: (seconds, nanoseconds) |
Source code in libs/shellfish/shellfish/sh.py
383 384 385 386 387 388 389 390 391 392 393 394 |
|
shellfish.sh.sep_join(path_strings: Iterator[str]) -> str
⚓︎
Join iterable of strings on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1319 1320 1321 |
|
shellfish.sh.sep_lstrip(fspath: FsPath) -> str
⚓︎
Left-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1329 1330 1331 |
|
shellfish.sh.sep_rstrip(fspath: FsPath) -> str
⚓︎
Right-strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1334 1335 1336 |
|
shellfish.sh.sep_split(fspath: FsPath) -> Tuple[str, ...]
⚓︎
Split a string on the current platform os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1314 1315 1316 |
|
shellfish.sh.sep_strip(fspath: FsPath) -> str
⚓︎
Strip a string of the current platform's os.path.sep value
Source code in libs/shellfish/shellfish/fs/__init__.py
1324 1325 1326 |
|
shellfish.sh.setenv(key: str, val: Optional[str] = None) -> Tuple[str, str]
⚓︎
Export/Set an environment variable
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
environment variable name/key |
required |
val
|
str
|
environment variable value |
None
|
Returns:
Type | Description |
---|---|
Tuple[str, str]
|
Tuple[str, str]: environment variable key/value pair |
Source code in libs/shellfish/shellfish/sh.py
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 |
|
shellfish.sh.shebang(fspath: FsPath) -> Union[None, str]
⚓︎
Get the shebang string given a fspath; Returns None if no shebang
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file that might have a shebang |
required |
Returns:
Type | Description |
---|---|
Union[None, str]
|
Optional[str]: The shebang string if it exists, None otherwise |
Examples:
>>> from inspect import getabsfile
>>> script = 'ashellscript.sh'
>>> with open(script, 'w') as f:
... f.write('#!/bin/bash\necho "howdy"\n')
25
>>> shebang(script)
'#!/bin/bash'
>>> from os import remove
>>> remove(script)
Source code in libs/shellfish/shellfish/fs/__init__.py
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
|
shellfish.sh.shell(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, shell: bool = True, extenv: bool = True, cwd: Optional[FsPath] = None, check: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done
⚓︎
Run a subprocess synchronously in current shell
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*popenargs
|
PopenArgs
|
Args given as |
()
|
args
|
Optional[PopenArgs]
|
Args as strings for the subprocess |
None
|
env
|
Optional[Dict[str, str]]
|
Environment variables as a dictionary (Default value = None) |
None
|
shell
|
bool
|
Run in shell or sub-shell; default is True for |
True
|
extenv
|
bool
|
Extend the environment with the current environment (Default value = True) |
True
|
cwd
|
Optional[FsPath]
|
Current working directory (Default value = None) |
None
|
check
|
bool
|
Check the outputs (generally useless) |
False
|
input
|
STDIN
|
Stdin to give to the subprocess |
None
|
verbose
|
bool
|
Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr |
False
|
timeout
|
Optional[int]
|
Timeout in seconds for the process if not None |
None
|
ok_code
|
Union[int, List[int], Tuple[int, ...], Set[int]]
|
Return code(s) to check if ok |
0
|
dryrun
|
bool
|
Don't run the subprocess |
False
|
Returns:
Type | Description |
---|---|
Done
|
Finished PRun object which is a dictionary, so a dictionary |
Source code in libs/shellfish/shellfish/sh.py
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 |
|
shellfish.sh.shplit(string: str, comments: bool = False, posix: bool = True) -> List[str]
⚓︎
Typed alias for shlex.split
Source code in libs/shellfish/shellfish/sh.py
1932 1933 1934 |
|
shellfish.sh.source(filepath: FsPath, _globals: bool = True) -> None
⚓︎
Execute/run a python file given a fspath and put globals in globasl
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
Path to python file |
required |
_globals
|
bool
|
Exec using globals |
True
|
Source code in libs/shellfish/shellfish/sh.py
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 |
|
shellfish.sh.stat(fspath: FsPath) -> os_stat_result
⚓︎
Return the os.stat_result object for a given fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
Path to file or directory |
required |
Returns:
Type | Description |
---|---|
stat_result
|
os.stat_result: stat_result object |
Source code in libs/shellfish/shellfish/fs/__init__.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 |
|
shellfish.sh.stat_async(fspath: FsPath) -> os.stat_result
async
⚓︎
Async version of os.lstat
Source code in libs/shellfish/shellfish/fs/_async.py
94 95 96 |
|
shellfish.sh.touch(fspath: FsPath, *, mkdirp: bool = True) -> None
⚓︎
Create an empty file given a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fspath
|
FsPath
|
File-system path for where to make an empty file |
required |
mkdirp
|
bool
|
Make parent directories if they don't exist |
True
|
Source code in libs/shellfish/shellfish/fs/__init__.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
|
shellfish.sh.tree(dirpath: FsPath, filterfn: Optional[Callable[[str], bool]] = None) -> str
⚓︎
Create a directory tree string given a directory path
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory string to make tree for |
required |
filterfn
|
Optional[Callable[[str], bool]]
|
Function to filter sub-directories and sub-files with |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Directory-tree string |
Examples:
>>> tmpdir = 'tree.doctest'
>>> from os import makedirs; makedirs(tmpdir, exist_ok=True)
>>> from pathlib import Path
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f)
... fspath = path.join(tmpdir, fspath)
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... makedirs(dirpath, exist_ok=True)
... Path(fspath).touch()
>>> print(tree(tmpdir))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
├── file1.txt
├── file2.txt
└── file3.txt
>>> print(tree(tmpdir, lambda s: _DirTree._default_filter(s) and not "file2" in s))
tree.doctest/
└── dir/
├── dir2/
│ ├── file1.txt
│ └── file3.txt
├── dir2a/
│ ├── file1.txt
│ └── file3.txt
├── file1.txt
└── file3.txt
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/sh.py
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 |
|
shellfish.sh.walk_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str]
⚓︎
Yield all paths beneath a given dirpath (defaults to os.getcwd())
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
FsPath
|
Directory path to walk down/through. |
'.'
|
abspath
|
bool
|
Yield the absolute path |
True
|
onerror
|
Optional[Callable[[OSError], Any]]
|
Function called on OSError |
None
|
topdown
|
bool
|
Not applicable |
True
|
followlinks
|
bool
|
Follow links |
False
|
check
|
bool
|
Check if dirpath exists |
True
|
Returns:
Type | Description |
---|---|
Iterator[str]
|
Generator object that yields directory paths (absolute or relative) |
Examples:
>>> tmpdir = 'walk_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
... ("dir", "file1.txt"),
... ("dir", "file2.txt"),
... ("dir", "file3.txt"),
... ("dir", "dir2", "file1.txt"),
... ("dir", "dir2", "file2.txt"),
... ("dir", "dir2", "file3.txt"),
... ("dir", "dir2a", "file1.txt"),
... ("dir", "dir2a", "file2.txt"),
... ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
... fspath = path.join(*f).replace('\\', '/')
... fspath = path.join(tmpdir, fspath).replace('\\', '/')
... dirpath = path.dirname(fspath)
... expected_files.append(fspath)
... expected_dirs.append(dirpath)
... _makedirs(dirpath, exist_ok=True)
... touch(fspath)
>>> expected_dirs = [el.replace('\\', '/') for el in sorted(set(expected_dirs))]
>>> from pprint import pprint
>>> pprint(expected_files)
['walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt']
>>> pprint(expected_dirs)
['walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2a']
>>> walk_gen_list = list(sorted(walk_gen(tmpdir)))
>>> walk_gen_list = [el.replace('\\', '/') for el in walk_gen_list]
>>> pprint(walk_gen_list)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> pprint(expected)
['walk_gen.doctest',
'walk_gen.doctest/dir',
'walk_gen.doctest/dir/dir2',
'walk_gen.doctest/dir/dir2/file1.txt',
'walk_gen.doctest/dir/dir2/file2.txt',
'walk_gen.doctest/dir/dir2/file3.txt',
'walk_gen.doctest/dir/dir2a',
'walk_gen.doctest/dir/dir2a/file1.txt',
'walk_gen.doctest/dir/dir2a/file2.txt',
'walk_gen.doctest/dir/dir2a/file3.txt',
'walk_gen.doctest/dir/file1.txt',
'walk_gen.doctest/dir/file2.txt',
'walk_gen.doctest/dir/file3.txt']
>>> walk_gen_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/shellfish/fs/__init__.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
shellfish.sh.wbytes(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> wbytes(fspath, bites_to_save)
20
>>> rbytes(fspath)
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 |
|
shellfish.sh.wbytes_async(filepath: FsPath, bites: bytes, *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Write/Save bytes to a fspath
The parameter 'bites' is used instead of 'bytes' so as to not redefine the built-in python bytes object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
filepath
|
FsPath
|
fspath to write to |
required |
bites
|
bytes
|
Bytes to be written |
required |
chmod
|
Optional[int]
|
chmod the fspath to this mode after writing |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs._async import rbytes_async, wbytes_async
>>> from asyncio import run as aiorun
>>> fspath = "wbytes_async.doctest.txt"
>>> bites_to_save = b"These are some bytes"
>>> aiorun(wbytes_async(fspath, bites_to_save))
20
>>> bites_to_save # they are bytes!
b'These are some bytes'
>>> aiorun(rbytes_async(fspath))
b'These are some bytes'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
shellfish.sh.wbytes_gen(filepath: FsPath, bytes_gen: Iterable[bytes], append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Write/Save bytes to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Iterable[bytes]
|
Bytes to be written |
required |
append
|
bool
|
Append to the file if True, overwrite otherwise; default is False |
False
|
chmod
|
Optional[int]
|
chmod the file after writing; default is None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
>>> from shellfish.fs import rbytes, wbytes
>>> fspath = "wbytes_gen.doctest.txt"
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save # they are bytes!
(b'These are some bytes... ', b'more bytes!')
>>> wbytes_gen(fspath, (b for b in bites_to_save))
35
>>> rbytes(fspath)
b'These are some bytes... more bytes!'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
shellfish.sh.wbytes_gen_async(filepath: FsPath, bytes_gen: Union[Iterable[bytes], AsyncIterable[bytes]], *, append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
Write/save bytes to a filepath from an (async)iterable/iterator of bytes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
bytes_gen
|
Union[Iterable[bytes], AsyncIterable[bytes]]
|
AsyncIterable/Iterator of bytes to write |
required |
append
|
bool
|
Append to the fspath if True; otherwise overwrite |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Examples:
>>> from os import remove
>>> from asyncio import run
>>> from shellfish.fs._async import wbytes_gen_async, rbytes_gen_async
>>> fspath = 'wbytes_gen_async.doctest.txt'
>>> bites_to_save = (b"These are some bytes... ", b"more bytes!")
>>> bites_to_save
(b'These are some bytes... ', b'more bytes!')
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> async def read():
... async for b in rbytes_gen_async(fspath, blocksize=4):
... print(b)
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> async def async_gen():
... for b in bites_to_save:
... yield b
>>> run(wbytes_gen_async(fspath, bites_to_save))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
>>> class AsyncIterable:
... def __aiter__(self):
... return async_gen()
>>> run(wbytes_gen_async(fspath, AsyncIterable()))
35
>>> run(read())
b'Thes'
b'e ar'
b'e so'
b'me b'
b'ytes'
b'... '
b'more'
b' byt'
b'es!'
>>> remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
shellfish.sh.where(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
; alias of shellfish.sh.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 |
|
shellfish.sh.which(cmd: str, path: Optional[str] = None) -> Optional[str]
⚓︎
Return the result of shutil.which
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 |
|
shellfish.sh.which_lru(cmd: str, path: Optional[str] = None) -> Optional[str]
cached
⚓︎
Return the result of shutil.which
and cache the results
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmd
|
str
|
Command/exe to find path of |
required |
path
|
str
|
System path to use |
None
|
Returns:
Type | Description |
---|---|
Optional[str]
|
Optional[str]: path to command/exe |
Source code in libs/shellfish/shellfish/sh.py
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 |
|
shellfish.sh.wjson(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, chmod: Optional[int] = None, append: bool = False, **kwargs: Any) -> int
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Append a newline to the end of the file |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
append
|
bool
|
Append to the file if True, overwrite otherwise; default |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dumpb |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from shellfish.fs import rjson, wjson
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
19
>>> rjson(fspath)
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "rjson_dict.doctest.json"
>>> wjson(fspath, data)
25
>>> rjson(fspath)
[['a', 1], ['b', 2], ['c', 3]]
>>> os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 |
|
shellfish.sh.wjson_async(filepath: FsPath, data: Any, *, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, append: bool = False, chmod: Optional[int] = None, **kwargs: Any) -> int
async
⚓︎
Save/Write json-serial-ize-able data to a fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
data
|
Any
|
json-serial-ize-able data |
required |
fmt
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
pretty
|
bool
|
Indented (2 spaces) or minify data (default=False) |
False
|
sort_keys
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
append_newline
|
bool
|
Sort the data keys if the data is a dictionary. |
False
|
default
|
Optional[Callable[[Any], Any]]
|
default function hook |
None
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to jsonbourne.JSON.dump |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bytes written |
Examples:
Imports:
>>> from asyncio import run
>>> from shellfish.fs._async import rjson_async, wjson_async
Dictionaries:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> fspath = "wjson_async_dict.doctest.json"
>>> run(wjson_async(fspath, data))
19
>>> run(rjson_async(fspath))
{'a': 1, 'b': 2, 'c': 3}
>>> import os; os.remove(fspath)
Lists:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> data = list(data.items())
>>> data # has tuples, but will be saved as strings
[('a', 1), ('b', 2), ('c', 3)]
>>> fspath = "wjson_async_list.doctest.json"
>>> run(wjson_async(fspath, data))
25
>>> run(rjson_async(fspath))
[['a', 1], ['b', 2], ['c', 3]]
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/_async.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
|
shellfish.sh.wstring(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
⚓︎
Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
String encoding to write file with |
'utf-8'
|
append
|
bool
|
Flag to append to file; default = False |
False
|
chmod
|
Optional[int]
|
Optional chmod to set on file |
None
|
Returns:
Type | Description |
---|---|
int
|
None |
Examples:
>>> from shellfish.fs import rstring, wstring
>>> fspath = "sstring.doctest.txt"
>>> wstring(fspath, r'Check out this string')
21
>>> rstring(fspath)
'Check out this string'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/shellfish/fs/__init__.py
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
shellfish.sh.wstring_async(filepath: FsPath, string: str, *, encoding: str = 'utf-8', append: bool = False, chmod: Optional[int] = None) -> int
async
⚓︎
(ASYNC) Save/Write a string to fspath
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
FsPath
|
fspath to write to |
required |
string
|
str
|
string to be written |
required |
encoding
|
str
|
File encoding (Default='utf-8') |
'utf-8'
|
append
|
bool
|
Append to the fspath if True; default is False |
False
|
chmod
|
Optional[int]
|
chmod the fspath if not None |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
number of bytes written |
Source code in libs/shellfish/shellfish/fs/_async.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|