๐Ÿ“ฆ da-x / rvim

๐Ÿ“„ python.snippets ยท 138 lines
1
2
3
4
5
6
7
8
9
10
11
12
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
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
88
89
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
129
130
131
132
133
134
135
136
137
138snippet newprog
#!/usr/bin/env python
# pylint: disable=all

def main():
    $0
    pass

if __name__ == "__main__":
    main()
endsnippet

snippet interact
import code
code.interact(local=locals())
endsnippet

snippet tempdir
import tempfile
import os

# Create a temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
    print(f'Temporary directory: {temp_dir}')

    # You can create files in the temporary directory
    temp_file_path = os.path.join(temp_dir, 'temp_file.txt')
    with open(temp_file_path, 'w') as temp_file:
        temp_file.write('Hello, world!')

    # At this point, the temporary file is in the temporary directory
    print(f'Temporary file: {temp_file_path}')
    print(f'Contents: {open(temp_file_path).read()}')
endsnippet

snippet download-file
import requests

def download_file(url, target_path):
    response = requests.get(url, stream=True)
    response.raise_for_status()
    with open(target_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

# Example usage:
download_file('http://example.com/bigfile.zip', '/path/to/destination/bigfile.zip')
endsnippet

snippet prettyprint
pp = pprint.PrettyPrinter(depth=3)
with open('/tmp/some-file.txt', 'w') as file:
    pp = pprint.PrettyPrinter(stream=file)
    pp.pprint(some_obj)
endsnippet

snippet handylog
def log_write_append(s: str) -> None:
    LOG_PATH = "/tmp/my-tracelog.log"
    from datetime import datetime
    import os
    import threading
    tid = threading.get_native_id()
    flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT
    fd = os.open(LOG_PATH, flags, 0o644)
    try:
        ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        pid = os.getpid()
        prefix = f"{ts} [{pid:7d}/{tid:7d}] "
        os.write(fd, (prefix + s + "\n").encode("utf-8"))
    finally:
        os.close(fd)
endsnippet

snippet standalone
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = []
# ///
def main():
    $0
    pass

if __name__ == "__main__":
    main()
endsnippet

snippet standalone_log
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = "~=3.13"
# dependencies = ["colorlog==6.10.1"]
# ///

import logging
from colorlog import ColoredFormatter

# Configure logger
logger = logging.getLogger('HelloWorldLogger')
logger.setLevel(logging.DEBUG)

# Create console handler with colored formatter
console_handler = logging.StreamHandler()
formatter = ColoredFormatter(
    "%(log_color)s%(asctime)s - %(levelname)s - %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S',
    log_colors={
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red',
    }
)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

def main():
    logger.debug("Debugging the Hello World program")
    # logger.info("Hello, World!")
    # logger.warning("This is a warning message")
    # logger.error("This is an error message")
    # logger.critical("This is a critical message")

if __name__ == "__main__":
    main()
endsnippet

snippet bash
def bash(script):
    import os
    r = os.spawnv(os.P_WAIT, "/bin/bash", ["bash", "-c", script])
    if r != 0:
        logger.error(f"failed executing {repr(script)}");
        raise Exception(f"failed executing {repr(script)}")
endsnippet