@@ -1391,4 +1391,336 @@ except <exception>:
1391
1391
< code>
1392
1392
```
1393
1393
1394
+ ### Complex Example
1395
+ ``` python
1396
+ try :
1397
+ < code_1>
1398
+ except < exception_a> :
1399
+ < code_2_a>
1400
+ except < exception_b> :
1401
+ < code_2_b>
1402
+ else :
1403
+ < code_2_c>
1404
+ finally :
1405
+ < code_3>
1406
+ ```
1407
+ * ** Code inside the ` 'else' ` block will only be executed if ` 'try' ` block had no exceptions.**
1408
+ * ** Code inside the ` 'finally' ` block will always be executed (unless a signal is received).**
1409
+
1410
+ ### Catching Exceptions
1411
+ ``` python
1412
+ except < exception> : ...
1413
+ except < exception> as < name> : ...
1414
+ except (< exception> , [... ]): ...
1415
+ except (< exception> , [... ]) as < name> : ...
1416
+ ```
1417
+ * ** Also catches subclasses of the exception.**
1418
+ * ** Use ` 'traceback.print_exc()' ` to print the error message to stderr.**
1419
+ * ** Use ` 'print(<name>)' ` to print just the cause of the exception (its arguments).**
1420
+ * ** Use ` 'logging.exception(<message>)' ` to log the exception.**
1421
+
1422
+ ### Raising Exceptions
1423
+ ``` python
1424
+ raise < exception>
1425
+ raise < exception> ()
1426
+ raise < exception> (< el> [, ... ])
1427
+ ```
1428
+
1429
+ #### Re-raising caught exception:
1430
+ ``` python
1431
+ except < exception> as < name> :
1432
+ ...
1433
+ raise
1434
+ ```
1435
+
1436
+ ### Exception Object
1437
+ ``` python
1438
+ arguments = < name> .args
1439
+ exc_type = < name> .__class__
1440
+ filename = < name> .__traceback__ .tb_frame.f_code.co_filename
1441
+ func_name = < name> .__traceback__ .tb_frame.f_code.co_name
1442
+ line = linecache.getline(filename, < name> .__traceback__ .tb_lineno)
1443
+ traceback = ' ' .join(traceback.format_tb(< name> .__traceback__ ))
1444
+ error_msg = ' ' .join(traceback.format_exception(exc_type, < name> , < name> .__traceback__ ))
1445
+ ```
1446
+
1447
+ ### Built-in Exceptions
1448
+ ``` text
1449
+ BaseException
1450
+ +-- SystemExit # Raised by the sys.exit() function.
1451
+ +-- KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
1452
+ +-- Exception # User-defined exceptions should be derived from this class.
1453
+ +-- ArithmeticError # Base class for arithmetic errors.
1454
+ | +-- ZeroDivisionError # Raised when dividing by zero.
1455
+ +-- AssertionError # Raised by `assert <exp>` if expression returns false value.
1456
+ +-- AttributeError # Raised when an attribute is missing.
1457
+ +-- EOFError # Raised by input() when it hits end-of-file condition.
1458
+ +-- LookupError # Raised when a look-up on a collection fails.
1459
+ | +-- IndexError # Raised when a sequence index is out of range.
1460
+ | +-- KeyError # Raised when a dictionary key or set element is missing.
1461
+ +-- MemoryError # Out of memory. Could be too late to start deleting vars.
1462
+ +-- NameError # Raised when an object is missing.
1463
+ +-- OSError # Errors such as “file not found” or “disk full” (see Open).
1464
+ | +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
1465
+ +-- RuntimeError # Raised by errors that don't fall into other categories.
1466
+ | +-- RecursionError # Raised when the maximum recursion depth is exceeded.
1467
+ +-- StopIteration # Raised by next() when run on an empty iterator.
1468
+ +-- TypeError # Raised when an argument is of wrong type.
1469
+ +-- ValueError # When an argument is of right type but inappropriate value.
1470
+ +-- UnicodeError # Raised when encoding/decoding strings to/from bytes fails.
1471
+ ```
1472
+
1473
+ #### Collections and their exceptions:
1474
+ ``` text
1475
+ +-----------+------------+------------+------------+
1476
+ | | List | Set | Dict |
1477
+ +-----------+------------+------------+------------+
1478
+ | getitem() | IndexError | | KeyError |
1479
+ | pop() | IndexError | KeyError | KeyError |
1480
+ | remove() | ValueError | KeyError | |
1481
+ | index() | ValueError | | |
1482
+ +-----------+------------+------------+------------+
1483
+ ```
1484
+
1485
+ #### Useful built-in exceptions:
1486
+ ``` python
1487
+ raise TypeError (' Argument is of wrong type!' )
1488
+ raise ValueError (' Argument is of right type but inappropriate value!' )
1489
+ raise RuntimeError (' None of above!' )
1490
+ ```
1491
+
1492
+ ### User-defined Exceptions
1493
+ ``` python
1494
+ class MyError (Exception ): pass
1495
+ class MyInputError (MyError ): pass
1496
+ ```
1497
+
1498
+
1499
+ Exit
1500
+ ----
1501
+ ** Exits the interpreter by raising SystemExit exception.**
1502
+ ``` python
1503
+ import sys
1504
+ sys.exit() # Exits with exit code 0 (success).
1505
+ sys.exit(< el> ) # Prints to stderr and exits with 1.
1506
+ sys.exit(< int > ) # Exits with passed exit code.
1507
+ ```
1508
+
1509
+
1510
+ Print
1511
+ -----
1512
+ ``` python
1513
+ print (< el_1> , ... , sep = ' ' , end = ' \n ' , file = sys.stdout, flush = False )
1514
+ ```
1515
+ * ** Use ` 'file=sys.stderr' ` for messages about errors.**
1516
+ * ** Use ` 'flush=True' ` to forcibly flush the stream.**
1517
+
1518
+ ### Pretty Print
1519
+ ``` python
1520
+ from pprint import pprint
1521
+ pprint(< collection> , width = 80 , depth = None , compact = False , sort_dicts = True )
1522
+ ```
1523
+ * ** Levels deeper than 'depth' get replaced by '...'.**
1524
+
1525
+
1526
+ Input
1527
+ -----
1528
+ ** Reads a line from user input or pipe if present.**
1529
+
1530
+ ``` python
1531
+ < str > = input (prompt = None )
1532
+ ```
1533
+ * ** Trailing newline gets stripped.**
1534
+ * ** Prompt string is printed to the standard output before reading input.**
1535
+ * ** Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.**
1536
+
1537
+
1538
+ Command Line Arguments
1539
+ ----------------------
1540
+ ``` python
1541
+ import sys
1542
+ scripts_path = sys.argv[0 ]
1543
+ arguments = sys.argv[1 :]
1544
+ ```
1545
+
1546
+ ### Argument Parser
1547
+ ``` python
1548
+ from argparse import ArgumentParser, FileType
1549
+ p = ArgumentParser(description = < str > )
1550
+ p.add_argument(' -<short_name>' , ' --<name>' , action = ' store_true' ) # Flag.
1551
+ p.add_argument(' -<short_name>' , ' --<name>' , type = < type > ) # Option.
1552
+ p.add_argument(' <name>' , type = < type > , nargs = 1 ) # First argument.
1553
+ p.add_argument(' <name>' , type = < type > , nargs = ' +' ) # Remaining arguments.
1554
+ p.add_argument(' <name>' , type = < type > , nargs = ' *' ) # Optional arguments.
1555
+ args = p.parse_args() # Exits on error.
1556
+ value = args.< name>
1557
+ ```
1558
+
1559
+ * ** Use ` 'help=<str>' ` to set argument description that will be displayed in help message.**
1560
+ * ** Use ` 'default=<el>' ` to set the default value.**
1561
+ * ** Use ` 'type=FileType(<mode>)' ` for files. Accepts 'encoding', but 'newline' is None.**
1562
+
1563
+
1564
+ Open
1565
+ ----
1566
+ ** Opens the file and returns a corresponding file object.**
1567
+
1568
+ ``` python
1569
+ < file > = open (< path> , mode = ' r' , encoding = None , newline = None )
1570
+ ```
1571
+ * ** ` 'encoding=None' ` means that the default encoding is used, which is platform dependent. Best practice is to use ` 'encoding="utf-8"' ` whenever possible.**
1572
+ * ** ` 'newline=None' ` means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.**
1573
+ * ** ` 'newline=""' ` means no conversions take place, but input is still broken into chunks by readline() and readlines() on every '\n', '\r' and '\r\n'.**
1574
+
1575
+ ### Modes
1576
+ * ** ` 'r' ` - Read (default).**
1577
+ * ** ` 'w' ` - Write (truncate).**
1578
+ * ** ` 'x' ` - Write or fail if the file already exists.**
1579
+ * ** ` 'a' ` - Append.**
1580
+ * ** ` 'w+' ` - Read and write (truncate).**
1581
+ * ** ` 'r+' ` - Read and write from the start.**
1582
+ * ** ` 'a+' ` - Read and write from the end.**
1583
+ * ** ` 't' ` - Text mode (default).**
1584
+ * ** ` 'b' ` - Binary mode (` 'br' ` , ` 'bw' ` , ` 'bx' ` , …).**
1585
+
1586
+ ### Exceptions
1587
+ * ** ` 'FileNotFoundError' ` can be raised when reading with ` 'r' ` or ` 'r+' ` .**
1588
+ * ** ` 'FileExistsError' ` can be raised when writing with ` 'x' ` .**
1589
+ * ** ` 'IsADirectoryError' ` and ` 'PermissionError' ` can be raised by any.**
1590
+ * ** ` 'OSError' ` is the parent class of all listed exceptions.**
1591
+
1592
+ ### File Object
1593
+ ``` python
1594
+ < file > .seek(0 ) # Moves to the start of the file.
1595
+ < file > .seek(offset) # Moves 'offset' chars/bytes from the start.
1596
+ < file > .seek(0 , 2 ) # Moves to the end of the file.
1597
+ < bin_file> .seek(±offset, < anchor> ) # Anchor: 0 start, 1 current position, 2 end.
1598
+ ```
1599
+
1600
+ ``` python
1601
+ < str / bytes > = < file > .read(size = - 1 ) # Reads 'size' chars/bytes or until EOF.
1602
+ < str / bytes > = < file > .readline() # Returns a line or empty string/bytes on EOF.
1603
+ < list > = < file > .readlines() # Returns a list of remaining lines.
1604
+ < str / bytes > = next (< file > ) # Returns a line using buffer. Do not mix.
1605
+ ```
1606
+
1607
+ ``` python
1608
+ < file > .write(< str / bytes > ) # Writes a string or bytes object.
1609
+ < file > .writelines(< collection> ) # Writes a coll. of strings or bytes objects.
1610
+ < file > .flush() # Flushes write buffer. Runs every 4096/8192 B.
1611
+ ```
1612
+ * ** Methods do not add or strip trailing newlines, even writelines().**
1613
+
1614
+ ### Read Text from File
1615
+ ``` python
1616
+ def read_file (filename ):
1617
+ with open (filename, encoding = ' utf-8' ) as file :
1618
+ return file .readlines()
1619
+ ```
1620
+
1621
+ ### Write Text to File
1622
+ ``` python
1623
+ def write_to_file (filename , text ):
1624
+ with open (filename, ' w' , encoding = ' utf-8' ) as file :
1625
+ file .write(text)
1626
+ ```
1627
+
1628
+
1629
+ Paths
1630
+ -----
1631
+ ``` python
1632
+ from os import getcwd, path, listdir, scandir
1633
+ from glob import glob
1634
+ ```
1635
+
1636
+ ``` python
1637
+ < str > = getcwd() # Returns the current working directory.
1638
+ < str > = path.join(< path> , ... ) # Joins two or more pathname components.
1639
+ < str > = path.abspath(< path> ) # Returns absolute path.
1640
+ ```
1641
+
1642
+ ``` python
1643
+ < str > = path.basename(< path> ) # Returns final component of the path.
1644
+ < str > = path.dirname(< path> ) # Returns path without the final component.
1645
+ < tup.> = path.splitext(< path> ) # Splits on last period of the final component.
1646
+ ```
1647
+
1648
+ ``` python
1649
+ < list > = listdir(path = ' .' ) # Returns filenames located at path.
1650
+ < list > = glob(' <pattern>' ) # Returns paths matching the wildcard pattern.
1651
+ ```
1652
+
1653
+ ``` python
1654
+ < bool > = path.exists(< path> ) # Or: <Path>.exists()
1655
+ < bool > = path.isfile(< path> ) # Or: <DirEntry/Path>.is_file()
1656
+ < bool > = path.isdir(< path> ) # Or: <DirEntry/Path>.is_dir()
1657
+ ```
1658
+
1659
+ ``` python
1660
+ < stat> = os.stat(< path> ) # Or: <DirEntry/Path>.stat()
1661
+ < real> = < stat> .st_mtime/ st_size/ … # Modification time, size in bytes, …
1662
+ ```
1663
+
1664
+ ### DirEntry
1665
+ ** Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.**
1666
+
1667
+ ``` python
1668
+ < iter > = scandir(path = ' .' ) # Returns DirEntry objects located at path.
1669
+ < str > = < DirEntry> .path # Returns whole path as a string.
1670
+ < str > = < DirEntry> .name # Returns final component as a string.
1671
+ < file > = open (< DirEntry> ) # Opens the file and returns a file object.
1672
+ ```
1673
+
1674
+ ### Path Object
1675
+ ``` python
1676
+ from pathlib import Path
1677
+ ```
1678
+
1679
+ ``` python
1680
+ < Path> = Path(< path> [, ... ]) # Accepts strings, Paths and DirEntry objects.
1681
+ < Path> = < path> / < path> [/ ... ] # First or second path must be a Path object.
1682
+ ```
1683
+
1684
+ ``` python
1685
+ < Path> = Path() # Returns relative cwd. Also Path('.').
1686
+ < Path> = Path.cwd() # Returns absolute cwd. Also Path().resolve().
1687
+ < Path> = Path.home() # Returns user's home directory (absolute).
1688
+ < Path> = Path(__file__ ).resolve() # Returns script's path if cwd wasn't changed.
1689
+ ```
1690
+
1691
+ ``` python
1692
+ < Path> = < Path> .parent # Returns Path without the final component.
1693
+ < str > = < Path> .name # Returns final component as a string.
1694
+ < str > = < Path> .stem # Returns final component without extension.
1695
+ < str > = < Path> .suffix # Returns final component's extension.
1696
+ < tup.> = < Path> .parts # Returns all components as strings.
1697
+ ```
1698
+
1699
+ ``` python
1700
+ < iter > = < Path> .iterdir() # Returns directory contents as Path objects.
1701
+ < iter > = < Path> .glob(' <pattern>' ) # Returns Paths matching the wildcard pattern.
1702
+ ```
1703
+
1704
+ ``` python
1705
+ < str > = str (< Path> ) # Returns path as a string.
1706
+ < file > = open (< Path> ) # Also <Path>.read/write_text/bytes().
1707
+ ```
1708
+
1709
+
1710
+ OS Commands
1711
+ -----------
1712
+ ``` python
1713
+ import os, shutil, subprocess
1714
+ ```
1715
+
1716
+ ``` python
1717
+ os.chdir(< path> ) # Changes the current working directory.
1718
+ os.mkdir(< path> , mode = 0o 777 ) # Creates a directory. Permissions are in octal.
1719
+ os.makedirs(< path> , mode = 0o 777 ) # Creates all path's dirs. Also: `exist_ok=False`.
1720
+ ```
1721
+
1722
+ ``` python
1723
+ shutil.copy(from , to) # Copies the file. 'to' can exist or be a dir.
1724
+ shutil.copytree(from , to) # Copies the directory. 'to' must not exist.
1725
+ ```
1394
1726
0 commit comments