Last active
November 10, 2023 17:08
-
-
Save miron/de23442b37d27942c256bf0a121fb2fe to your computer and use it in GitHub Desktop.
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
from IPython.terminal.prompts import Prompts, Token | |
class MyPrompt(Prompts): | |
def in_prompt_tokens(self, cli=None): | |
return [ ( Token.Prompt, "λ ",), ] | |
def out_prompt_tokens(self, cli=None): | |
return [] | |
ip = get_ipython() # only in ipython | |
ip.prompts = MyPrompt(ip) # A minimal prompt for ipython | |
# Run external python file in blender | |
import bpy | |
import os | |
filename = os.path.join("D:/Documents/blender/modules/", "ut.py") | |
exec(compile(open(filename).read(), filename, 'exec')) | |
from subprocess import run, sys; run([sys.executable, '-m', 'pip', 'install', '<packagename>']) # install module from within python shell | |
from subprocess import run; run('pip install <packagename>', shell=True) # shorter version | |
from subprocess import run; run(['pip', 'install', '<packagename>']) # yes, shorter | |
import os; f = os.path.join.(os.getcwd(), 'file.txt'); os.chmod(f, 0o600) # change file to rw for owner only | |
import psutil; psutil.Process().memory_info().rss/(1024 ** 2) # show memory size of running python shell in MB | |
import os; os.getcwd() # view current directory | |
import this # Zen of Python | |
import antigravity # You are flying! How? | |
os.environ['HOME'] # Get environment variable | |
os.environ.get('HOME') # sam, but different, but same | |
os.getenv('HOME') # Wrapper to os.environ.get('HOME') | |
with open('filename') as f: | |
read_data = f.read() | |
with open('filename', 'w') as f: | |
f.write("#First Line\n" + read_data) # insert at beginning of file | |
@classmethod # class method constructor with cls as parameter | |
@staticmethod # a static method with no arguments | |
@dataclass # define fields to include parameters/methods like __init__(), __repr__, ___eq___, some default to true already. Less typing | |
print("\033c", end='') # clear screen in REPL | |
# max() with lambda function as key parameter, list comprehension, str.split() and dict.get(), - before dict reverses order | |
max([word for word in 'Who is the richest, Bill Gates, Jeff Bezos, Warren Buffet, Mark Zuckerberg or Elon Musk?'.split()], | |
key=lambda k: {'Warren': 124.3, 'Bill': 132.3, 'Elon': 264.6, 'Jeff': 177.5, 'Mark': 75.2}.get(k,0)) | |
import string; [ord(char) for char in string.ascii_uppercase] # show unicode code point values (order) | |
(lambda p: (w := [c.lower()for c in p if c.isalpha()]) == w[::-1])('') # palindrome checker, put string in last parenthesis | |
(lambda p: (w := [c.lower()for c in p if c.isalpha()]).__eq__(w[::-1]))('') | |
(lambda p: (w := [map(str.lower, (c for c in p if c.isalpha()))]) == w[::-1])('') | |
print("You have", coins:=5, f'coin{"s" if coins !=1 else ""}') # singular/plural | |
sum([num < 0 for num in [-1, -2, 3, 4]]) # occurencies of negative numbers | |
{str(n):n for n in range(1,11)} # generate dict of numbers with string of number as keys | |
{**{str(n):n for n in range(2,11)},'A': [11,1], 'K': 10, 'Q': 10, 'J': 10} # unpack dict into dict | |
{k: {'a':1, 'b':2, 'c':3, 'd':4}[k] for k in ['b','d']} # filter dict with keys in list | |
{{'a':1, 'b':2, 'c':3, 'd':4}[k] for k in ['b','d']} # just the values | |
[{'a':1, 'b':2, 'c':3, 'd':4}[k] for k in ['b','d','b']] # same key, multiple values to list | |
[i for i, c in enumerate(l) if c == 'x'] # list of index numbers in list l for every occurence of 'x' | |
[print("Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i)for i in range(1,101)] # FizzBuzz oneliner, no output of list of None in script. | |
sum([100, 10, 20, 50, 30, 25][-i-1] * 1.03**i for i in range(6)) # Yearly Cashflows Future Value 3% p.a. | |
print('', end = '') # if you want to print 2 pandas series, without single space from newline in second series | |
a = b.copy(); a = b[:] # list.copy() and slicing when assign create new list. | |
a[:] = [] # Changing list with slice doesn't create new list, assign without slice does | |
a = 1,2,3 # tuple without parenthesis | |
import importlib; importlib.reload(<module>) # reload module without leaving REPL | |
exit() # Stop script depends on site module | |
raise SystemExit # or raise SystemExit() exits script, does not depend on site module | |
a, b = [(1,2),(3,4)] # first tuple to a, second to b | |
a, b = zip(*[(1,2),(3,4)]) # first element of tuples to a, second to b | |
{'mus' : sum}['mus']((3,3)) # asign sum function as value of dict and calls it | |
{'' : print}['']('Hello world') # same | |
[print][0]('Hello world') # with list | |
(print,)[0]('Hello world') # as tuple | |
next(iter({print}))('Hallo World') # as set | |
[line.strip() for line in lines[:1]] # clean list elements from '\n', ommit header from csv list | |
g = (i for i in range(2,100)if all([i%j for j in range(2,i)])) # prime number generator to 100, next(g) | |
g = (lambda x: (i for i in range(2,x)if all([i%j for j in range(2,i)])))(100) # same, but with 100 as parameter | |
(lambda x: f'{x=}')(5) # 'x=5', debugging specifier | |
list(range(-5, 257)) # integers in this range are objects in Python | |
a=257;b=257;a is b # Optimized in Pyton interpreter but not in iPython | |
(a := 'y'*4096) is (b :='y'*4096) # True, but not beyond, AST optimizer | |
'Go Sports! #Sports'.split('#')[1] # gives you the hashtag | |
a = (x for x in [1,2,3]) | |
next(a, None) # finishes iteration with None instead StopIteration | |
import ast; print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4)) # check which expression, comprehension or object |
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
# vscode | |
"pythonArgs": ["-i"], # launch.json, launches script in interactive console | |
"python.formatting.autopep8Args": ["--ignore=E731"], # settings.json, don't format my lambdas | |
set editing-mode vi in .inputrc, clear screen with ESC Ctrl-L in REPL | |
^Z, fg # go from python interpreter to bash and back again. |
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
pylint.exe $(git ls-files '*.py') # Linting for all your python files in repository | |
ipython --TerminalInteractiveShell.editing_mode=vi # ipython with vim keybindings | |
pip freeze | %{$_.split('==')[0]} | %{pip install --upgrade $_} # update all packages in powershell | |
python -im pdb /dev/null # just start the python debugger | |
python -im pdb nul # same in powershell | |
youtube-dl -f bestvideo-bestaudio "url" # download best versions of your videos | |
pydoc <modulename> # offline documentation in the terminal like help() in the python shell | |
send2trash.exe # python programm that sends files to trash instead of deleting it permanently | |
python -m ensurepip # bootstrap pip installer | |
python -m site # show site-package directories | |
export API_KEY=***; python3 -c 'import os; print(os.environ["API_KEY"])' # Use enviroment variable in Python | |
jupyter nbconvert --execute --to markdown README.ipynb # convert notebook to markdown file | |
# Vim keybindings in Python interpreter | |
.vim.py: | |
import readline | |
readline.parse_and_bind('set editing-mode vim') | |
PYTHONSTARTUP=$HOME/.vim.py; export PYTHONSTARTUP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment