Skip to content

Commit 1ed0e65

Browse files
committed
util: add rprint and print2
1 parent 0a3d24c commit 1ed0e65

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

‎nico.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,10 @@ def validate_cookie(cookies):
7070
# it's recommended to set proxy to '' instead of None, otherwise
7171
# some redirected requests may not actually use the proxy settings.
7272
# see https://github.com/psf/requests/issues/6153
73-
7473
proxy = ''
7574
elif proxy == 'auto':
7675
sys_proxies = getproxies()
77-
if proxy := sys_proxies.get('http'):
76+
if proxy := sys_proxies.get('http', ''): # if failed, proxy would be ''
7877
print(f'INFO: Automatically use system proxy {proxy}')
7978
# I don't think system proxy would be missing scheme ever, but just in case
8079
if proxy and '://' not in proxy:

‎util.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ def save(self, f):
254254

255255
def multi_col_print(data, columns=5):
256256
'''Print a list of data in a table with columns'''
257+
# pip install rich
257258
from rich.console import Console
258259
from rich.table import Table
259260

@@ -265,10 +266,38 @@ def multi_col_print(data, columns=5):
265266
for i in range(row_count):
266267
row = data[i::row_count]
267268
table.add_row(*row)
268-
269269
console = Console()
270270
console.print(table)
271271

272+
def rprint(*args, **kwargs):
273+
'''
274+
Print function that uses rich library to print (This is different from
275+
rich.print() because that does not support additional arguments like `style`.)
276+
The console obj is created only once and reused.
277+
'''
278+
# pip install rich
279+
from rich.console import Console
280+
if not hasattr(rprint, '_console'):
281+
rprint._console = Console()
282+
rprint._console.print(*args, **kwargs)
283+
284+
def print2(*args, **kwargs):
285+
'''
286+
Custom print function that manages line endings.
287+
If a previous print call ended without a newline (e.g., end=''),
288+
and the current call implies a newline (e.g., default end or end='\n'),
289+
an explicit newline is printed first to terminate the previous line.
290+
The state _newlined is stored as an attribute of the print2 function itself.
291+
'''
292+
from builtins import print as builtin_print
293+
if not hasattr(print2, '_newlined'):
294+
print2._newlined = True
295+
end = kwargs.pop('end', '\n')
296+
if end.endswith('\n') and not print2._newlined:
297+
builtin_print()
298+
print2._newlined = True if end.endswith('\n') else False
299+
builtin_print(*args, **kwargs, end=end)
300+
272301
def array_to_range_text(a, sep=', ', dash='-'):
273302
s = ''
274303
prev_seg = None

0 commit comments

Comments
 (0)