DEV Community

Alex Spinov
Alex Spinov

Posted on

Python One-Liners That Replace Entire Shell Scripts

I used to write 50-line bash scripts for things Python does in one line.

Here are 15 one-liners I use daily.

File Operations

Start a web server (current directory)

python3 -m http.server 8080
Enter fullscreen mode Exit fullscreen mode

Replaces: nginx config + setup for quick file sharing.

Find duplicate files

python3 -c "import os,hashlib; seen={}; [print(f'DUPE: {f}') for r,d,files in os.walk('.') for f in files if (h:=hashlib.md5(open(os.path.join(r,f),'rb').read()).hexdigest()) in seen or seen.update({h:f}).__class__.__name__=='NoneType' and False]"
Enter fullscreen mode Exit fullscreen mode

Okay that's ugly. Here's the readable version:

python3 << 'EOF'
import os, hashlib
seen = {}
for root, dirs, files in os.walk('.'):
    for name in files:
        path = os.path.join(root, name)
        file_hash = hashlib.md5(open(path, 'rb').read()).hexdigest()
        if file_hash in seen:
            print(f'DUPE: {path} == {seen[file_hash]}')
        else:
            seen[file_hash] = path
EOF
Enter fullscreen mode Exit fullscreen mode

Pretty-print JSON

cat ugly.json | python3 -m json.tool
Enter fullscreen mode Exit fullscreen mode

Replaces: jq (which you have to install separately).

Serve JSON as API

python3 -c "from http.server import *; import json; handler=type('H',(BaseHTTPRequestHandler,),{'do_GET':lambda s:(s.send_response(200),s.send_header('Content-type','application/json'),s.end_headers(),s.wfile.write(json.dumps({'status':'ok','data':[1,2,3]}).encode()))}); HTTPServer(('',8080),handler).serve_forever()"
Enter fullscreen mode Exit fullscreen mode

One-line mock API. Perfect for frontend development.

Data Processing

CSV to JSON

python3 -c "import csv,json,sys; print(json.dumps(list(csv.DictReader(open(sys.argv[1]))),indent=2))" data.csv
Enter fullscreen mode Exit fullscreen mode

Count lines in all Python files

python3 -c "import os; print(sum(len(open(os.path.join(r,f)).readlines()) for r,d,fs in os.walk('.') for f in fs if f.endswith('.py')))"
Enter fullscreen mode Exit fullscreen mode

Find largest files

python3 -c "import os; files=[(os.path.join(r,f),os.path.getsize(os.path.join(r,f))) for r,d,fs in os.walk('.') for f in fs]; [print(f'{s/1024/1024:.1f}MB {p}') for p,s in sorted(files,key=lambda x:-x[1])[:10]]"
Enter fullscreen mode Exit fullscreen mode

Network

Check if a website is up

python3 -c "import urllib.request; print('UP' if urllib.request.urlopen('https://example.com').status==200 else 'DOWN')"
Enter fullscreen mode Exit fullscreen mode

Get your public IP

python3 -c "import urllib.request; print(urllib.request.urlopen('https://api.ipify.org').read().decode())"
Enter fullscreen mode Exit fullscreen mode

Download a file

python3 -c "import urllib.request; urllib.request.urlretrieve('https://example.com/file.zip', 'file.zip'); print('Done')"
Enter fullscreen mode Exit fullscreen mode

Text Processing

Generate a random password

python3 -c "import secrets,string; print(''.join(secrets.choice(string.ascii_letters+string.digits+'!@#$') for _ in range(20)))"
Enter fullscreen mode Exit fullscreen mode

Base64 encode/decode

echo 'hello' | python3 -c "import sys,base64; print(base64.b64encode(sys.stdin.buffer.read()).decode())"
echo 'aGVsbG8K' | python3 -c "import sys,base64; print(base64.b64decode(sys.stdin.read()).decode())"
Enter fullscreen mode Exit fullscreen mode

URL encode

python3 -c "import urllib.parse; print(urllib.parse.quote('hello world & stuff'))"
Enter fullscreen mode Exit fullscreen mode

System

Watch a directory for changes

python3 -c "import time,os; prev={}; exec('while True:\n files={os.path.join(r,f):os.path.getmtime(os.path.join(r,f)) for r,d,fs in os.walk(\".\") for f in fs}\n for f in set(files)-set(prev): print(f\"NEW: {f}\")\n for f in set(prev)-set(files): print(f\"DEL: {f}\")\n for f in set(files)&set(prev):\n  if files[f]!=prev[f]: print(f\"MOD: {f}\")\n prev=files\n time.sleep(1)')"
Enter fullscreen mode Exit fullscreen mode

Kill process by name

python3 -c "import os,signal,subprocess; [os.kill(int(p),signal.SIGTERM) for p in subprocess.check_output(['pgrep','-f','process_name']).decode().split() if p]"
Enter fullscreen mode Exit fullscreen mode

The Point

Python is already on your machine. Before you brew install or apt-get another CLI tool, check if Python can do it in one line.


More Python tools: Python API Client Template | Awesome Python Automation | All repos

Top comments (0)