当前位置: 首页>>代码示例>>Python>>正文


Python Pipe.fileno方法代码示例

本文整理汇总了Python中multiprocessing.Pipe.fileno方法的典型用法代码示例。如果您正苦于以下问题:Python Pipe.fileno方法的具体用法?Python Pipe.fileno怎么用?Python Pipe.fileno使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在multiprocessing.Pipe的用法示例。


在下文中一共展示了Pipe.fileno方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
 def __init__(self):
     r, w = Pipe(duplex=False)
     _set_non_blocking(r.fileno())
     _set_non_blocking(w.fileno())
     close_on_exec(r.fileno())
     close_on_exec(w.fileno())
     self._writer = w
     self._reader = r
开发者ID:JinsongBian,项目名称:pulsar,代码行数:10,代码来源:posixsystem.py

示例2: ConsoleProxy

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
class ConsoleProxy(object):
    def __init__(self):
        self._read, self._write = Pipe(duplex=True)

    def fileno(self):
        return self._read.fileno()

    def read(self):
        data = self._read.recv()
        if data["type"] == "completer":
            result = command_root.match(data["line"], data["hints"])
        elif data["type"] == "parser":
            try:
                result = command_root.parse(data["line"])
            except Command.NotFound as e:
                if str(e) != "":
                    result = str(e)
                else:
                    result = "No such command '{:s}'".format(data["line"])
            except Command.SyntaxError as e:
                result = str(e)
        else:
            result = ""

        self._read.send(result)

    def completer(self, line, hints):
        self._write.send({"type" : "completer", "line" : line, "hints" : hints})
        return self._write.recv()

    def parser(self, line):
        self._write.send({"type" : "parser", "line" : line})
        return self._write.recv()
开发者ID:fredriklindberg,项目名称:chromesthesia,代码行数:35,代码来源:chromesthesia.py

示例3: ProcessApplication

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
class ProcessApplication(Application):
    """Run application class in subprocess."""

    def __init__(self, reaktor, target, name=''):
        Application.__init__(self, None, name)
        self.target = target
        self._reaktor = reaktor
        self._process = None
        self.parent = None
        self.child = None
        self.transport = None
        self.runner = None

    def start(self):
        signal.signal(signal.SIGCHLD, self._sigchld)
        self.parent, self.child = Pipe(duplex=True)
        logging.debug("parent conn %d, child %d",
                      self.parent.fileno(), self.child.fileno())
        self.transport = ConnectedTransport(self._reaktor, self.parent, self)
        self.runner = _Subprocess(self.target, self.child, self.config)
        self._process = Process(target=self.runner.run)
        self._process.start()

    def _close(self, timeout):
        self._process.join(timeout)
        if self.transport is not None:
            # this closes also parent channel
            self.transport.close()
            self.transport.del_channel()
        self.child = self.parent = self.transport = None

    def _sigchld(self, signum, frame):
        self._close(0.5)

    def stop(self):
        self._process.terminate()
        self._close(2.0)

    def send(self, data):
        """Send data to application."""
        self.parent.send(data)

    def recv(self, data):
        """Handle data received from subprocess application."""
        if isinstance(data, Exception):
            self.log.error("Subprocess exception: %s", str(data))
            raise data
        self.received(data)

    def event_readable(self, transport):
        assert(transport == self.transport)
        data = self.transport.socket.recv()
        self.log.debug("received from app: %s", str(data))
        if data is not None:
            self.recv(data)

    def event_error(self, transport):
        typ, ex, tb = sys.exc_info()
        if typ != KeyboardInterrupt:
            self.log.debug("process: %s", str(ex))
开发者ID:hrautila,项目名称:SXproto,代码行数:62,代码来源:apps.py

示例4: main

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
def main():
    """ Main function, gets arguments from sys.argv and starts chat and listen
        thread """
    parser = ArgumentParser(description='Chat program')
    parser.add_argument('-l', '--local-port', default=12345, type=int)
    parser.add_argument('-n', '--name', default='apa', help='Your name')
    args = parser.parse_args()
    host = Address(socket.gethostname(), args.local_port)

    new_chat_pipe_out, new_chat_pipe_in = Pipe(False)
    state = State(args.name, host)
    input_control = InputControl(args.name, host, state)
    l_thread = GenericThread(listen_thread, host, state, new_chat_pipe_in)
    l_thread.start()

    print(">", end=" ")
    sys.stdout.flush()
    while True:
        try:
            input_ready, _, _ = select.select([sys.stdin,
                                              new_chat_pipe_out.fileno()],
                                              [], [], 0)
            if sys.stdin in input_ready:
                # Command from command line
                line = sys.stdin.readline()
                if line:
                    input_control.handle_input(line)
                else:
                    # Shutdown on EOF
                    input_control.shutdown()
            if new_chat_pipe_out.fileno() in input_ready:
                # Got message from friend, but chat is not open
                friend_name = new_chat_pipe_out.recv()
                state.connect_to(friend_name)
            # Check if any chat has been closed
            state.check_closed_chat()
            time.sleep(0.1)

        except (EOFError, KeyboardInterrupt):
            state.shutdown()
            l_thread.terminate()
开发者ID:Grulfen,项目名称:pychat,代码行数:43,代码来源:main.py

示例5: start_streaming_search

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
def start_streaming_search():
    global subprocess_to_main1, subprocess_to_main2, search_subprocess
    subprocess_to_main1, subprocess_to_main2 = Pipe(duplex=False)
    search_subprocess = Process(target=streaming_search, kwargs={
        "subprocess_to_main": subprocess_to_main2,
        "search_targets": search_targets,
        "filter_level": filter_level,
        "english_only": english_only
    })
    search_subprocess.start()
    IOLoop.instance().add_handler(
        subprocess_to_main1.fileno(),
        partial(on_streaming_search_msg, subprocess_to_main1),
        IOLoop.READ)
开发者ID:BWu1024,项目名称:twitter-remote-wall,代码行数:16,代码来源:wall.py

示例6: _make_tab

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
    def _make_tab(self, uri: str = 'about:blank', switch_to: bool = False):
        """ Make a tab.

        """

        socket_id, child = self._add_tab(switch_to)

        main_pipe, child_pipe = Pipe()

        com_dict = Manager().dict({socket_id: child_pipe})

        child['com-tup'] = (main_pipe, com_dict)
        child['pid'] = 0
        child['uri'] = uri
        self._windows[socket_id] = child

        self._glib.io_add_watch(main_pipe.fileno(), self._glib.IO_IN,
                                self._callback, child)

        return com_dict
开发者ID:zepto,项目名称:webbrowser2,代码行数:22,代码来源:webkit2_test.py

示例7: DaemonService

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
class DaemonService(BaseService):
    """
    In charge to receive messages and send responses to subscribed clients
    """
    def __init__(self, name, config):
        super(DaemonService, self).__init__(name, config)
        self.proc = Process(target=self.main)
        self.proc.daemon = True
        self.parent_end, self.child_end = Pipe()
        self.listen_fileno = self.parent_end.fileno()
    def listen (self, timeout=None):
        if not self.child_end.poll(timeout):
            return
        msg = self.child_end.recv()
        self.exec_action(msg)
    def add_event(self, msg):
        self.logger.debug("Piping message: %s" % msg)
        self.parent_end.send(msg)
    def send_action(self, msg):
        self.child_end.send(msg)
    def recv_action(self):
        return self.parent_end.recv()
开发者ID:modulix,项目名称:gwss,代码行数:24,代码来源:DaemonService.py

示例8: Worker

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]
class Worker(Process):
    def __init__(self, endpoint, workport=23456, logport=23457, workerID=None, print_local=True):
        Process.__init__(self)
        self.endpoint = endpoint
        self.workport = workport
        self.logport = logport
        self.workerID = workerID
        self.print_local = print_local

        self._is_stdsocket_setup = False

        if self.workerID is None:
            self.workerID = "worker-" + str(uuid4())

        self.ipcURI = "ipc:///tmp/splark_" + self.workerID + ".ipc"

        # Data id: cloudpickle
        self.data = {}
        self.unsent_stdout = ""

    def setupWorker(self):
        self.inner_recv_pipe, inner_stdout = Pipe(duplex=False)
        # Make the pipe look like the inner worker's stdout. Surprisingly, this works.
        inner_stdout.write = inner_stdout.send
        inner_stdout.flush = lambda: None
        self.inner_worker = InnerWorker(self.ipcURI, daemon=True, stdout=inner_stdout, stderr=inner_stdout)
        self.inner_worker.start()

        self.working = False
        self.workingID = None

    def setupZMQ(self):
        self.ctx = zmq.Context()

        # Setup syncronous comms to master
        self.master_socket = MasterConnection(self.ctx, self.workerID.encode("ascii"))
        self.master_socket.connect(self.endpoint + ":" + str(self.workport))

        # Send the initial worker ID to start a transaction going
        self.master_socket.send_connect()

        # Setup async stdio/stderr
        self.stdsocket = self.ctx.socket(zmq.PUSH)
        self.stdsocket.connect(self.endpoint + ":" + str(self.logport))
        self._is_stdsocket_setup = True

        # Setup IPC to inner worker
        self.inner_socket = self.ctx.socket(zmq.REQ)
        self.inner_socket.bind(self.ipcURI)

    def setupPoller(self):
        self.poller = zmq.Poller()
        self.poller.register(self.master_socket, zmq.POLLIN)
        self.poller.register(self.inner_socket, zmq.POLLIN)
        self.poller.register(self.inner_recv_pipe.fileno(), zmq.POLLIN)

    def setup(self):
        self.log("Initializing.")
        self.setupZMQ()
        self.setupWorker()
        self.setupPoller()
        self.log("Initialization complete.")

    def log(self, *args):
        short_name = self.workerID.split("worker-")[1][:8]
        print_args = ("WORKER " + short_name + " >>>",) + args
        if self.print_local:
            print(*print_args)
        # Buffer this message to be sent over stdout.
        self.unsent_stdout += "\n" + " ".join(print_args) + "\n"
        self.flush_stdout_buffer()

    # All _handle_* functions map 1:1 with API calls
    # They all return a pyobject, which is the serialized
    # response to the call
    def _handle_SETDATA(self, id, blob):
        self.data[id] = blob
        return Commands.OK

    def _handle_DELDATA(self, id):
        try:
            del self.data[id]
            return Commands.TRUE
        except KeyError:
            return Commands.FALSE

    def _handle_GETDATA(self, id):
        try:
            return self.data[id]
        except KeyError as e:
            return toCP(e)

    def _handle_LISTDATA(self):
        return toCP(list(self.data.keys()))

    def _handle_ISWORKING(self):
        return Commands.TRUE if self.working else Commands.FALSE

    def _handle_RESETWORKER(self):
        self.inner_worker.terminate()
#.........这里部分代码省略.........
开发者ID:belisarius222,项目名称:splark,代码行数:103,代码来源:worker.py

示例9: SoundAnalyzer

# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import fileno [as 别名]

#.........这里部分代码省略.........
                # Pre-calculate offset into power array
                prev_power_idx = scale * chunk * prev_freq / sample
                power_idx = scale * chunk * freq / sample
                if (prev_power_idx - power_idx) >= 1:
                    break
            bins.insert(0, [power_idx, prev_power_idx])

        bins.insert(0, [0, (scale * chunk * freq / sample)])
        self._bins = bins

        # Calculate EQ weights
        # Range from 2^0 to 2^6 (64) stretched over the number of bins
        self._eq = np.power(2, np.linspace(0, 6, len(self._bins)))

        self._running = Value('i', 0)
        self._pipe, pipe = Pipe(duplex=False)

        self._p = Process(target=self._run, args=(self._running, pipe))
        self._p.daemon = True
        self._p.start()
        pipe.close()

    def close(self):
        self._running.value = -1
        self._p.terminate()
        self._p.join()

    def start(self):
        self._running.value = 1

    def stop(self):
        self._running.value = 0

    def fileno(self):
        return self._pipe.fileno()

    def _run(self, running, pipe):
        self._pipe.close()
        self._pipe = pipe
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        while running.value >= 0:
            if running.value == 1:
                self._analyze(running, pipe)
            else:
                time.sleep(0.1)

    def _analyze(self, running, pipe):
        pa = pyaudio.PyAudio()
        sample_fmt = pa.get_format_from_width(self._sample_width / 8)
        input = pa.open(format=sample_fmt, input=True,
            channels=self._channels, rate=self._sample,
            frames_per_buffer=self._chunk)

        sample_size = self._sample_width / 8
        frame_len = self._chunk * sample_size * self._channels

        if sample_size == 1:
            data_type = 'b'
            unpack_fmt = "%db" % int(frame_len)
        elif sample_size == 2:
            data_type = 'h'
            unpack_fmt = "%dh" % int(frame_len / 2)

        spectrum = [0] * len(self._bins)
开发者ID:fredriklindberg,项目名称:chromesthesia,代码行数:69,代码来源:sound.py


注:本文中的multiprocessing.Pipe.fileno方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。