tips
10 tips Scripting
One command, setting or habit at a time about Scripting: what it does, the line to copy and a caveat or two.
Standard library 6
-
Print a diff of two texts from a script, in the same format as git and diff -u.
import difflib -
Write a file safely by writing a temp copy first and then replacing the original.
import json, os, tempfile -
Counts items in any list and returns the most frequent ones.
from collections import Counter -
Returns the full path of a command, or None when it is not installed.
import shutil -
Temporarily changes the working directory for a block and restores it afterwards.
from contextlib import chdir -
Sorts items so every one comes after the things it depends on.
from graphlib import TopologicalSorter
Python one-liners 2
-
Strips shared indentation from a multi-line string so it can sit in indented code.
from textwrap import dedent -
Removes an exact prefix from a string, unlike lstrip which strips a set of characters.
>>> 'Arthur: three!'.lstrip('Arthur: ')
Windows 2
-
Call a REST API and work with the fields directly, without parsing JSON yourself.
$r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest -
Runs a PowerShell command and reports how long it took to finish.
Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }
Nothing in this filter yet.