import socket try: socket.socket().bind(('127.0.0.1', 9050)) tor_port_free = True except (OSError, socket.error): tor_port_free = False