from subprocess import Popen as popenimport reimport osfname = 'tmp.txt'fout = open(fname, 'wb')p = popen('netstat -nao', stdout=fout)p.wait()p = popen('tasklist', stdout=fout)p.wait()fout.close()fin = open(fname, 'rb')buf = fin.read()fin.close()os.remove(fname)p1 = ':(\d{1,5}) +?.+?LISTENING +?(\d{1,5})'p2 = '(.+?) +?(\d{1,5}) Console|(.+?) +?(\d{1,5}) Services'ports = {}for i in re.finditer(p1, buf): _port = i.group(1) _pid = i.group(2) if not ports.has_key(_pid): ports[_pid] = [_port] else: ports[_pid].append(_port)names = {}c = 0for i in re.finditer(p2, buf): _name = i.group(1) _pid = i.group(2) if _name: names[_pid] = _name else: _name = i.group(3) _pid = i.group(4) names[_pid] = _nameprint '-' * 79for d in names: if ports.has_key(d): print 'Process', names[d], '(pid %s)' % d, 'ports:', ', '.join(ports[d])print '-' * 79raw_input('Press ENTER key to continue ...')
buf = ''p = popen('netstat -nao', bufsize=1024, stdout=pipe)buf += p.stdout.read()p = popen('tasklist', bufsize=1024, stdout=pipe)buf += p.stdout.read()
...>>> pop = subprocess.Popen('cmd /c dir', stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=False)>>> print pop.stdout.read()...
程序代码: [选择]...>>> pop = subprocess.Popen('cmd /c dir', stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=False)>>> print pop.stdout.read()...
试试psutil 模块,你可以更优雅的实现你要的功能,而且更重要的是它是夸平台的。
psutil 官方没有放出 编译版本 相当麻烦啊...自己编译也很麻烦...