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


Python Process.close方法代码示例

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


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

示例1: SocketServer

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
class SocketServer(asyncore.dispatcher):
	def __init__(self, host, port):
		self.clients = Clients()
		asyncore.dispatcher.__init__(self)
		self.port = port
		self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
		self.set_reuse_addr()
		self.bind((host, port))
		self.bind = host
		self.listen(5)

	def __sock_process(self, socket):
		self.clients.append(socket)
		self.socketHandler = SocketHandler(self, socket)

	#handle when a connection is established and a connect() has been issued, add client
	def handle_accept(self):
		pair = self.accept()
		if pair != None:
			socket, addr = pair
			self.s = Process(target=self.__sock_process(socket), args=[])

			try:
				self.s.start()
			except:
				self.s.terminate()

	#handle when connection is closed and remove client
	def handle_close(self):
		self.clients.remove_all()
		self.s.close()
		print 'Sockets closed'
开发者ID:syurchi,项目名称:mobile-gamepad-control,代码行数:34,代码来源:socketServer.py

示例2: tryforkwindows

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
def tryforkwindows(n):
    if n == 1:
        print('Parent process %s.' % os.getpid())
        sec = 3
        p = Process(target=run_proc, args=('test', sec))
        print('Child process will start ...')
        p.start()
        childlast = 15
        while childlast >= 0:
            print('# Parent (%s) and its child (%s).' % (os.getpid(), p.pid))
            time.sleep(1)
            childlast -= 1

        # Not successful!
        # os.kill(p.pid, signal.CTRL_C_EVENT)
        # p.join()

        print('Parent (%s) kills child (%s)' % (os.getpid(), p.pid))
        p.terminate()
        print('Child process end.')

    if n == 2:
        print('Parent process %s.' % os.getpid())
        process_num = 16
        p = Pool(process_num)
        for i in range(process_num):
            p.apply_async(long_time_task, args=(i,))

        print('Waiting for all subprocesses done...')
        p.close()
        p.join()
        print('All subprocesses done.')

    if n == 3:
        cmd = 'ping www.baidu.com'
        print(cmd)
        r = subprocess.call(cmd.split())
        print('Exit code = ', r)

    if n == 4:
        q = Queue()
        pw = Process(target=q_write, args=(q,))
        pr = Process(target=q_read, args=(q,))
        pr.start()
        pw.start()
        pw.join()
        pr.terminate()

    return
开发者ID:chao98,项目名称:Python,代码行数:51,代码来源:tryfork.py

示例3: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')
"""对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
就可以同时跑5个进程。
由于Pool的默认大小是CPU的核数,如果你不幸拥有8核CPU,你要提交至少9个子进程才能看到上面的等待效果。"""

#子进程
"""很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。
subprocess模块可以让我们启动一个子进程,然后控制其输入和输出
下面的例子演示了如何在Python代码中运行命令nslookup www.python.org,这和命令行直接运行的效果是一样的:"""
import subprocess
print('$ nslookup www.python.org')
r = subprocess.call(['nslookup','www.python.org'])
开发者ID:lxw15337674,项目名称:Language_learning,代码行数:33,代码来源:mulpro.py

示例4: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
def long_time_task(name):
    print "Run task %s (%s)" % (name, os.getpid())
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print "Task %s runs %0.2f seconds" % (name, (end - start))


if __name__ == "__main__":
    print "Parent process %s" % os.getpid()
    p = Pool(9)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print "Wait for all subprocess done..."
    p.close()  # close 后进不能在加入process
    p.join()
    print "All subprocess end..."

# 进程间通讯 Queue 或 Pipes
from multiprocessing import Process, Queue
import os, random, time


def write(q):
    for value in ["a", "b", "c"]:
        print "Put %s to queue..." % value
        q.put(value)
        time.sleep(4)

开发者ID:kveen,项目名称:Python-1,代码行数:30,代码来源:多进程.py

示例5: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
print '\n进程池'

def long_time_task(name):
    print 'Run task %s (%s)...' %(name, os.getpid())
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print 'Task %s runs %0.2f seconds.' %(name, (end - start))
    
if __name__ == '__main__':        #表示程序作为主程序执行,而不是使用import作为模块导入
    print 'Parents process %s.' %os.getpid()
    p = Pool()
    for i in range(9):
        p.apply_async(long_time_task, args = (i, ))
    print 'Waiting for all subprocesses done...'
    p.close() # 调用close()之后就不能继续添加新的Process了。
    p.join()  # 对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close()。
    print 'All subprocesses done.'   
    
    
print '\n多线程'

import threading
# 新线程执行代码:
def loop():
    print 'thread %s is running...' %threading.current_thread().name
    n = 0
    while n < 5:
        n = n + 1
        print 'thread %s >>> %s ' %(threading.current_thread().name, n)
        time.sleep(1)
开发者ID:zengxpqq,项目名称:python,代码行数:33,代码来源:multiprocess.py

示例6: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
import os, time, random

def long_time_task(name):
    print('run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('task %s runs %0.2f seconds.' % (name, (end- start)))

if __name__ == '__main__':
    print('parent process %s.' % os.getpid())
    p = Pool(4) # run 4 processes each time
    for i in range(5):
        p.apply_async(long_time_task, args = (i,))
    print('waiting for all subprocesses done...')
    p.close() # close is necessary before join
    p.join()
    print('all subprocesses done.')

# When running this in spyder, it keeps waiting like forever.

# It works in cmd.
# open cmd
# python D:\python\python\Note7-liao.py
# (you need to input the absolute path)
#%%

# subprocess

import subprocess
开发者ID:dawnyoung,项目名称:python,代码行数:32,代码来源:Note7-liao.py

示例7: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
import os,time,random

def long_time_task(name):
	print('Run task %s (%s)...' %(name,os.getpid()))
	start = time.time()
	time.sleep(random.random() * 3)
	end = time.time()
	print('Tasks %s runs %0.2f sconds.' %(name,(end-start)))
	
if __name__=='__main__':
	print('Parent process %s.' % os.getpid())
	p = Pool(4)
	for i in range(5):
		p.apply_async(long_time_task,args=(i,))
	print('Waiting for all subprocesses done...')
	p.close() #调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
	p.join()  #对Pool对象调用join()方法会等待所有子进程执行完毕
	print('All subprocesses done.')
    #task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。
	#由于Pool的默认大小是CPU的核数,如果你不幸拥有8核CPU,你要提交至少9个子进程才能看到上面的等待效果。
	

#子进程 
print("==============subprocess=====================")
import subprocess
r=subprocess.call(['nslookup','www.baidu.com'])
print('Exit code:',r)



#进程间通信
开发者ID:7colorlotus,项目名称:pythonLearn,代码行数:33,代码来源:multiprocessingSample.py

示例8: print

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
if __name__ == '__main__':
    # 创建进程
    print('Parent process %s.' % (os.getpid()))
    p = Process(target=run_proc, args=('test',))  # 创建子进程,需要函数,参数是元组
    print('Child process will start.')
    p.start()  # 启动进程
    p.join()  # 等待子进程结束才继续运行
    print('Child process end.')

    # 进程池
    print('Parent process %s.' % os.getpid())
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done.')
    p.close()  # close 之后不能够再添加新的进程
    p.join()  # 在join之前必须调用close
    print('All done')

    # 子进程
    print('$ nslookup www.python.org')
    r = subprocess.call(['nslookup', 'www.python.org'])
    print('Exit code:', r)

    # 进程间通信
    q = Queue()

    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    pw.start()  # 启动写进程
    pr.start()  # 启动读进程
开发者ID:iceSong,项目名称:python_study,代码行数:33,代码来源:multipro.py

示例9: long_time_task

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import close [as 别名]
'''若要启动大量子进程,可用进程池的方式批量创建子进程'''
from  multiprocessing import Pool
def long_time_task(name):
	print('Run task %s (%s)...' % (name, os.getpid()))
	start = time.time()
	time.sleep(random.random() * 3)
	end = time.time()
	print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__ =='__main__':
	print ('parent process %s.' % os.getpid()) #os.getpid()可获取父进程的id
	p=Pool(3) #创建一个进程池p,包含3个进程
	for i in range(5):
		p.apply_async(long_time_task,args=(i,))
	print('Waiting for all subprocesses done...')
	p.close() #关闭pool
	p.join() #等待所有子进程结束后在继续往下执行,用于进程间同步
	print('All subprocesses done')

'''subprocess模块可方便地启动一个子进程,然后控制其输入和输出'''
import subprocess
print('$ nslookup www.python.org')
r=subprocess.call(['nslookup','www.python.org'])
print('Exit code:', r)

'''进程间通信,multiprocessing模块包装了底层的机制,提供了Quene,Pipes
等多种方式交换数据'''
from  multiprocessing import Process,Queue
def write(q):
	print('Process to write: %s' % os.getpid())
	for value in ['A', 'B', 'C']:
开发者ID:echoTomei,项目名称:PythonCode,代码行数:33,代码来源:multiprocess.py


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