Mercurial > hg > Lemuriformes
diff 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 diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemuriformes/port.py Sun Dec 10 17:42:52 2017 -0800 @@ -0,0 +1,30 @@ +#!/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()