Last active
August 20, 2022 08:01
-
-
Save nathants/741b066af9faa15f3ed50ed6cf677d67 to your computer and use it in GitHub Desktop.
3 bash functions for quick python oneliners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# The MIT License (MIT) | |
# Copyright (c) 2022-present Nathan Todd-Stone | |
# https://en.wikipedia.org/wiki/MIT_License#License_terms | |
PY_IMPORTS=" | |
import datetime | |
import string | |
import random | |
import math | |
import time | |
import itertools | |
import collections | |
import functools | |
import fcntl | |
import os | |
import sys | |
import pprint | |
import json | |
import re | |
from pprint import pformat | |
import signal | |
import uuid | |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) | |
" | |
# exec a python snippet and print the result, stdin is not used | |
# >> p '60*60*24' | |
# 86400 | |
p() { | |
python -c " | |
$PY_IMPORTS | |
val = $@ | |
if val: | |
if isinstance(val, list): | |
print(' '.join(map(str, val))) | |
else: | |
print(val) | |
" | |
} | |
# exec a python snippet and print the result, stdin is read (not streamed per line) and assigned to "i" | |
# >> echo -e 'a\nb\nc' | py 'random.choice(i.splitlines())' | |
# c | |
py() { | |
python -c " | |
$PY_IMPORTS | |
i = sys.stdin.read() | |
val = $@ | |
if val: | |
if isinstance(val, list): | |
print('\n'.join(map(str, val))) | |
else: | |
print(val) | |
" | |
} | |
# exec a python snippet and print the result, stdin is streamed per line and assigned to "i" | |
# >> echo -e 'a\nb\nc\n' | pys 'f"{i.upper()}:{j}"' | |
# A:0 | |
# B:1 | |
# C:2 | |
pys() { | |
python -c " | |
$PY_IMPORTS | |
j = 0 | |
while True: | |
i = sys.stdin.readline().strip() | |
if not i: | |
break | |
val = $@ | |
if val: | |
if isinstance(val, list): | |
print(' '.join(map(str, val))) | |
else: | |
print(val) | |
j += 1 | |
" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment