5 Powerful Python one-liners
Python one-liners can be just as powerful as a long and tedious program written in another language designed to do the same thing. In other languages this would be nearly impossible, but in Python, it’s a lot easier to do. The trick is to think of something that will “do a lot with a little.” Most importantly, reading and writing about Python one-liners (e.g., in this post) is a lot of fun! There’s even a whole subculture around who can write the shortest code for a given problem.
1. Share your Wi-Fi password with your guests by printing it as qr code
echo "WIFI:T:WPA;S:NETWORK_NAME;P:PASSWORD_HERE;H:;" | qr --output=wifi.png
To run this command you need to install two dependencies:
pip install pillow
and pip install qrcode
2. CSV to JSON
python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"
3. Apply regular expression to lines from stdin
[another command] | python -c "import sys,re;[sys.stdout.write(re.sub('PATTERN', 'SUBSTITUTION', line)) for line in sys.stdin]"
OK, this one there are other tools that can accomplish the same with a shorter command. But what I like about it is that is less likely to face incompatibility, as for instance sed
, that might have different implementations across Linux and Mac.
4. Profile a python script
python -m cProfile foo.py
Check out how to use it here.
5. Start a Webserver on your current directory
$ python -m SimpleHTTPServer 8000
or on python3
$ python -m http.server
I used a lot in the past to share files between to machines inside the same network.
Do you know other useful one-liners, please share in the comments.