view lemuriformes/port.py @ 17:4793f99b73e0

[lemuriformes] utility functions
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:42:52 -0800
parents
children
line wrap: on
line source

#!/usr/bin/env python

import argparse
import socket
import sys


def get_free_port():
    """get a free port on localhost"""

    s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)
    s.bind(('localhost', 0))
    address, port = s.getsockname()
    s.close()
    return port


def main(args=sys.argv[1:]):
    """CLI to get a free port on localhost"""

    # parse command line
    parser = argparse.ArgumentParser(description=get_free_port.__doc__)
    options = parser.parse_args()

    # print an open port
    print (get_free_port())


if __name__ == '__main__':
    main()