views:

72

answers:

1

In linux, I can use lsof -i as in the following function:

def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid

Is there a cross-platform way to figure this out?

As a relevant reference, once I know the process id, the psutil library is very nice and lets me determine all sorts of useful process information for it in a cross-platform way. I just can't get the first part to work (finding the pid) cross-platform at the moment.


If not familiar with the lsof -i switch, the output looks like below (after launching a python process that opens a TCP socket listening on port 1234):

$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)
+1  A: 

This answer is more of a tangent to your question, but if you can find OS-specific ways but nothing strictly portable, I'd make your module like the following

def find_port_owner_windows(p):
    doit()

def find_port_owner_linux(p):
    doit2()

port_finders = {'nt': find_port_owner_windows,
                'posix': find_port_owner_linux}

try:
    find_port_owner = port_finders[os.name]
except KeyError:
    raise RuntimeError("No known port finder for your OS (%s)" % os.name)
Daenyth
Definitely a tangent, but thanks! I'm looking for a cross-platform way to do it, where the solution preferably isn't "figure out how to do it in the each of the platforms and dispatch a call in your code based on os.name or sys.platform". Although if that's all that is available, then so it goes.
Russ