0

第一篇在这里,我必须说我对一般的编程有点业余......我在osx上使用python 2.7.5子进程模块来读取名为dns-sd的实用程序的输出。

目标是找出在我的网络上运行的 SSH 文件服务器。使用“dns-sd -B _ssh._tcp”。在以下用途中工作正常:

from sys import *
from subprocess import *

class ProcessNAS(object):
    def __init__ (self, name):
        self.name = name
        self.status = False
        self.process = None

    def StartCheck(self):
        print "Checking for NAS..."
        stdout.flush()
        self.process = Popen( ["dns-sd", "-B", "_ssh._tcp", "."], stdout=PIPE )

        while True:
            line = self.process.stdout.readline()[:-1]
            print line
            if "Add" in line and self.name in line:
                self.status = True
                print "NAS '" + self.name + "' is available."
            elif "Rmv" in line and self.name in line:
                self.status = False
                print "NAS '" + self.name + "' is unavailable."


newCheckNAS = ProcessNAS("Drobo-FS")
newCheckNAS.StartCheck()

请注意,这是一个“实时”实用程序,如果 Python 脚本继续运行,则 dns-sd 输出的新行将通过打印自动显示。这是一个典型的输出:

Checking for NAS...
Browsing for _ssh._tcp
DATE: ---Tue 02 Jul 2013---
19:44:30.670  ...STARTING...
Timestamp     A/R Flags if Domain       Service Type       Instance Name
19:48:07.061  Add     2  4 local.       _ssh._tcp.         Drobo-FS
NAS 'Drobo-FS' is available.

我遇到的问题是,一旦我执行 newCheckNAS.StartCheck(),程序的其余部分只需等待 dns-sd 实用程序完成以继续。但是这个实时实用程序永远不会停止,它需要在后台继续监控。

我查看了各种线程、多处理甚至 pybonjour 模块,但我并不真正了解它们是如何工作的……我想我必须启动一个运行该实用程序的线程和另一个线程来收听它?

4

1 回答 1

0

这是作为新进程运行的类的一个非常基本的实现。这将允许您在主脚本/进程中继续执行,如果您想对子进程的输出执行任何操作,则需要使用某种进程间通信(即docs中描述multiprocessing的共享内存数据结构)父母。

from sys import *
from subprocess import *
import multiprocessing

class ProcessNAS(multiprocessing.Process):
    def __init__ (self, name):
        self.name_ = name
        self.status = False
        self.process = None
        super(ProcessNAS, self).__init__(target=self.StartCheck)

    def StartCheck(self):
        print "Checking for NAS..."
        stdout.flush()
        self.process = Popen( ["dns-sd", "-B", "_ssh._tcp", "."], stdout=PIPE )

        while True:
            line = self.process.stdout.readline()[:-1]
            print line
            if "Add" in line and self.name_ in line:
                self.status = True
                print "NAS '" + self.name_ + "' is available."
            elif "Rmv" in line and self.name_ in line:
                self.status = False
                print "NAS '" + self.name_ + "' is unavailable."

newCheckNAS = ProcessNAS("Drobo-FS")
newCheckNAS.start()  # <-- instead of StartCheck(), call start()

import time
time.sleep(4)
newCheckNAS.terminate()  # <-- now have two processes - able to kill the child
于 2013-07-03T00:14:02.317 回答