18. One-LinersΒΆ

In this chapter I will show you some one-liner Python commands which can be really helpful.

Simple Web Server

Ever wanted to quickly share a file over a network? Well you are in luck. Python has a feature just for you. Go to the directory which you want to serve over the network and write the following code in your terminal:

# Python 2
python -m SimpleHTTPServer

# Python 3
python -m http.server

Pretty Printing

You can print a list and dictionary in a beautiful format in the Python repl. Here is the relevant code:

from pprint import pprint

my_dict = {'name': 'Yasoob', 'age': 'undefined', 'personality': 'awesome'}
pprint(my_dict)

This is more effective on dict s. Moreover, if you want to pretty print json quickly from a file then you can simply do:

cat file.json | python -m json.tool

Profiling a script

This can be extremely helpful in pinpointing the bottlenecks in your scripts:

python -m cProfile my_script.py

Note: cProfile is a faster implementation of profile as it is written in c

CSV to json

Run this in the terminal:

python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"

Make sure that you replace csv_file.csv to the relevant file name.

List Flattening

You can quickly and easily flatten a list using itertools.chain.from_iterable from the itertools package. Here is a simple example:

a_list = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(a_list)))
# Output: [1, 2, 3, 4, 5, 6]

# or
print(list(itertools.chain(*a_list)))
# Output: [1, 2, 3, 4, 5, 6]

One-Line Constructors

Avoid a lot of boilerplate assignments when initializing a class

class A(object):
    def __init__(self, a, b, c, d, e, f):
        self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})

Additional one-liners can be found on the Python website.