show line numbers in conde snippets

This commit is contained in:
Marcello 2023-10-20 18:22:46 +02:00
parent cd1df0e376
commit 255a68d673
82 changed files with 1249 additions and 1251 deletions

View file

@ -2,7 +2,7 @@
## Creating a parser
```py
```py linenums="1"
import argparse
parser = argparse.ArgumentParser(description="description", allow_abbrev=True)
@ -25,7 +25,7 @@ parser = argparse.ArgumentParser(description="description", allow_abbrev=True)
## [Adding Arguments](https://docs.python.org/3/library/argparse.html#the-add-argument-method)
```py
```py linenums="1"
ArgumentParser.add_argument("name_or_flags", nargs="...", action="...")
```
@ -47,7 +47,7 @@ ArgumentParser.add_argument("name_or_flags", nargs="...", action="...")
`store`: This just stores the argument's value. This is the default action.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
@ -56,7 +56,7 @@ Namespace(foo='1')
`store_const`: This stores the value specified by the const keyword argument. The `store_const` action is most commonly used with optional arguments that specify some sort of flag.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
@ -65,7 +65,7 @@ Namespace(foo=42)
`store_true` and `store_false`: These are special cases of `store_const` used for storing the values True and False respectively. In addition, they create default values of False and True respectively.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
@ -76,7 +76,7 @@ Namespace(foo=True, bar=False, baz=True)
`append`: This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
@ -85,7 +85,7 @@ Namespace(foo=['1', '2'])
`append_const`: This stores a list, and appends the value specified by the const keyword argument to the list. (Note that the const keyword argument defaults to None.) The `append_const` action is typically useful when multiple arguments need to store constants to the same list. For example:
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
@ -96,7 +96,7 @@ Namespace(types=[<class 'str'>, <class 'int'>])
`count`: This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:
**Note**: the default will be None unless explicitly set to 0.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
@ -107,7 +107,7 @@ Namespace(verbose=3)
`version`: This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:
```py
```py linenums="1"
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
@ -117,7 +117,7 @@ PROG 2.0
`extend`: This stores a list, and extends each argument value to the list. Example usage:
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
>>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
@ -133,7 +133,7 @@ The `nargs` keyword argument associates a different number of command-line argum
`N` (an integer): N arguments from the command line will be gathered together into a list.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
@ -147,7 +147,7 @@ Namespace(bar=['c'], foo=['a', 'b'])
For optional arguments, there is an additional case: the option string is present but not followed by a command-line argument. In this case the value from const will be produced.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
@ -161,7 +161,7 @@ Namespace(bar='d', foo='d')
`*`: All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with `nargs='*'`, but multiple optional arguments with `nargs='*'` is possible.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
@ -172,7 +172,7 @@ Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
`+`: All command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn't at least one command-line argument present.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args(['a', 'b'])
@ -184,7 +184,7 @@ PROG: error: the following arguments are required: foo
`argparse.REMAINDER`: All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.
```py
```py linenums="1"
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo')
>>> parser.add_argument('command')
@ -195,7 +195,7 @@ Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
## Parsing Arguments
```py
```py linenums="1"
# Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.
ArgumentParser.parse_args(args=None, namespace=None)

View file

@ -2,7 +2,7 @@
## FTP CLASSES
```py
```py linenums="1"
ftplib.FTP(host="", user="", password="", acct="")
# if HOST => connect(host)
# if USER => login(user, password, acct)
@ -13,7 +13,7 @@ ftplib.FTP_TLS(host="", user="", password="", acct="")
## EXCEPTIONS
```py
```py linenums="1"
ftplib.error_reply # unexpected error from server
ftplib.error_temp # temporary error (response codes 400-499)
ftplib.error_perm # permanent error (response codes 500-599)
@ -23,7 +23,7 @@ ftplib.all_errors # tuple of all exceptions
## FTP OBJECTS
```py
```py linenums="1"
# method on text files: -lines
# method on binary files: -binary

View file

@ -34,7 +34,7 @@ WHITESPACE can be inserted between any pair of tokens.
## Usage
```python
```python linenums="1"
# serialize obj as JSON formatted stream to fp
json.dump(obj, fp, cls=None, indent=None, separators=None, sort_keys=False)
@ -90,7 +90,7 @@ Conversions (Python -> Json):
## Extending JSONEncoder (Example)
```python
```python linenums="1"
import json
class ComplexEncoder(json.JSONEncoder):
@ -103,7 +103,7 @@ class ComplexEncoder(json.JSONEncoder):
## Retrieving Data from json dict
```python
```python linenums="1"
data = json.loads(json)
data["key"] # retrieve the value associated with the key
data["outer key"]["nested key"] # nested key value retrieval

View file

@ -2,7 +2,7 @@
## Configuration
```python
```python linenums="1"
# basic configuration for the logging system
logging.basicConfig(filename="relpath", level=logging.LOG_LEVEL, format=f"message format", **kwargs)
# DATEFMT: Use the specified date/time format, as accepted by time.strftime().
@ -76,7 +76,7 @@ Log Levels (Low To High):
- error: `40`
- critical: `50`
```python
```python linenums="1"
logging.debug(msg) # Logs a message with level DEBUG on the root logger
logging.info(msg) # Logs a message with level INFO on the root logger
logging.warning(msg) # Logs a message with level WARNING on the root logger

View file

@ -2,7 +2,7 @@
High-level file operations
```python
```python linenums="1"
# copy file src to fil dst, return dst in most efficient way
shutil.copyfile(src, dst)
# dst MUST be complete target name

View file

@ -1,6 +1,6 @@
# SMTPlib Module
```python
```python linenums="1"
import smtplib
# SMTP instance that encapsulates a SMTP connection

View file

@ -9,7 +9,7 @@ In this context, sockets are assumed to be associated with a specific socket add
## Socket Creation & Connection
```python
```python linenums="1"
import socket
# socket over the internet, socket is a stream of data
@ -21,7 +21,7 @@ socket.close() # close connection
## Making HTTP Requests
```python
```python linenums="1"
import socket
HTTP_Method = "GET http://url/resource HTTP/version\n\n".encode() # set HTTP request (encoded string from UTF-8 to bytes)
socket.send(HTTP_Method) # make HTTP request

View file

@ -4,14 +4,14 @@
To use the module, you must first create a Connection object that represents the database.
```python
```python linenums="1"
import sqlite3
connection = sqlite3.connect("file.db")
```
Once you have a `Connection`, you can create a `Cursor` object and call its `execute()` method to perform SQL commands.
```python
```python linenums="1"
cursor = connection.cursor()
cursor.execute(sql)
@ -31,7 +31,7 @@ it makes your program vulnerable to an [SQL injection attack](https://en.wikiped
Put `?` as a placeholder wherever you want to use a value, and then provide a _tuple of values_ as the second argument to the cursor's `execute()` method.
```python
```python linenums="1"
# Never do this -- insecure!
c.execute("SELECT * FROM stocks WHERE symbol = value")
@ -50,7 +50,7 @@ c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
### Writing Operations to Disk
```python
```python linenums="1"
cursor = connection.cursor()
cursor.execute("SQL")
connection.commit()
@ -58,7 +58,7 @@ connection.commit()
### Multiple SQL Instructions
```python
```python linenums="1"
connection = sqlite3.connect("file.db")
cur = con.cursor()
cur.executescript("""
@ -73,7 +73,7 @@ con.close()
### Retrieving Records
```python
```python linenums="1"
# Fetches the next row of a query result set, returning a single sequence.
# Returns None when no more data is available.
cursor.fetchone()

View file

@ -2,7 +2,7 @@
## Time
```py
```py linenums="1"
# epoch: elapsed time in seconds (in UNIX starts from 01-010-1970)
import time # UNIX time
variable = time.time () # returns the time (in seconds) elapsed since 01-01-1970
@ -42,7 +42,7 @@ var = time.perf_counter () # returns the current running time
## Datetime
```py
```py linenums="1"
import datetime
today = datetime.date.today () # returns current date
today = datetime.datetime.today () # returns the current date and time

View file

@ -1,6 +1,6 @@
# Unittest Module
```py
```py linenums="1"
import unittest
import module_under_test