Skip to content

Instantly share code, notes, and snippets.

@nathants
Last active August 20, 2022 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathants/741b066af9faa15f3ed50ed6cf677d67 to your computer and use it in GitHub Desktop.
Save nathants/741b066af9faa15f3ed50ed6cf677d67 to your computer and use it in GitHub Desktop.
3 bash functions for quick python oneliners
#!/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