本文整理汇总了Python中multiprocessing.Process.kill方法的典型用法代码示例。如果您正苦于以下问题:Python Process.kill方法的具体用法?Python Process.kill怎么用?Python Process.kill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.Process
的用法示例。
在下文中一共展示了Process.kill方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
def main():
p = Process(target=kinect_sender)
p.start()
host, port = '0.0.0.0', 12345
print "Running server at {host}:{port}".format(host=host, port=port)
http_server = WSGIServer((host, port), app)
http_server.serve_forever()
p.kill()
示例2: main
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
def main():
p = Process(target=opengazer_sender)
p.start()
#host, port = '192.168.43.9', 55555
host, port = socket.gethostbyname(socket.gethostname()), 55555
print "Running server at {host}:{port}".format(host=host, port=port)
http_server = WSGIServer((host, port), app)
http_server.serve_forever()
p.kill()
示例3: main
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
def main():
'''Función mainl del programa'''
p = Process(target=kinect_simulator)
p.start()
host, port = '0.0.0.0', 8888
print "Running server at {host}:{port}".format(host=host, port=port)
#gevent.spawn(retransmisor)
#gevent.spawn(sender)
http_server = WSGIServer((host, port), app)
http_server.serve_forever()
p.kill()
示例4: main
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
def main():
# Parse command line options
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-n', '--name', dest='name', default='A') # This is our DHT key - temporary!!!
parser.add_option('-p', '--httpport', dest='http_port', default=None)
parser.add_option('-u', '--udpport', dest='udp_port', default=None)
parser.add_option('-f', '--pipe', dest='pipe_test', default=None)
(options, args) = parser.parse_args()
name = options.name
http_port = None
if options.http_port:
http_port = int(options.http_port)
udp_port = None
if options.udp_port:
udp_port = int(options.udp_port)
pipe_test = options.pipe_test # Pipe for talking to test harness
http_ui = True
log.info("server listening on udp_port="+str(udp_port)+", http_port="+str(http_port))
# Named full duplex pipe for communicating between main process and UI/UDP
# server subprocess
pipe_server, pipe_ui = Pipe()
# Start UDP server subprocess
p_server = Process(target=start_server, args=(name, pipe_server, udp_port, pipe_test))
p_server.start()
# Choose which UI to use (http is better for testing multiple instances on same machine)
if http_ui and http_port:
p_ui = Process(target=start_ui, args=(pipe_ui, http_port))
p_ui.start()
p_ui.join()
p_ui.kill()
# else:
# # OSX status bar version not working with python 2.7 on OSX 10.6
# from userinterface import OSXstatusbaritem
# OSXstatusbaritem.start(pipeUI)
# return
p_server.join()
p_server.kill()
示例5: page
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
async def page(setup_settings, msend):
logging.getLogger().addHandler(logging.StreamHandler())
# backend_app and test_app are basically the same thing
# but we must create two so they don't reuse each others'
# database connections, which causes OperationalError
test_app = create_app()
backend_app = create_app()
celery.conf.task_always_eager = True
# we rely test_app it to setup the database
with test_app.app_context():
DB.create_all()
# we pass backend_app to the sub process that will respond to our frontend
host, port = settings.SERVICE_URL.split("://")[1].split(":")
p = Process(target=run_simple, args=(host, int(port), backend_app))
p.start()
# launch the browser
opts = {"headless": True}
if os.getenv("GOOGLE_CHROME_BIN"):
opts["executablePath"] = os.getenv("GOOGLE_CHROME_SHIM")
browser = await launch(opts)
page = await browser.newPage()
# at the same time we use the test_app to execute queries inside the tests
with test_app.app_context():
yield page
# terminate browser and backend app
p.terminate()
await browser.close()
time.sleep(0.1)
if p.is_alive():
p.kill()
# we also rely on test_app to purge the database
with test_app.app_context():
DB.session.remove()
DB.drop_all()
redis_store.flushdb()
示例6: __init__
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
class Listener:
def __init__(self):
self.name = ''
self.author = ''
self.description = ''
self.running = False
self.options = {}
self.__conn = None
self.__thread = None
def run(self):
return
def __run(self):
self.__conn = Client(('localhost', 60000), authkey=ipc_pass)
self.run()
def start(self):
self.__thread = Process(target=self.__run, daemon=True)
self.__thread.start()
self.running = True
def dispatch_event(self, event, msg):
self.__conn.send((event, msg))
data = ()
try:
data = self.__conn.recv()
except EOFError:
pass
return data
def stop(self):
self.__thread.kill()
self.running = False
def __getitem__(self, key):
return self.options[key]['Value']
def __setitem__(self, key, value):
self.options[key]['Value'] = value
示例7: ZeroServer
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
class ZeroServer(object):
event_listeners = set()
event_queue = Queue()
def __init__(self, *args, **kwargs):
self.SaltClient = APIClient()
self.event_listener_proc = Process(target=subprocess_read_events, args=(self.event_queue,))
self.event_listener_proc.start()
self.event_processor = Greenlet.spawn(process_events, self)
super(ZeroServer, self).__init__(*args, **kwargs)
def __del__(self, *args, **kwargs):
self.event_listener_proc.kill()
self.event_processor.kill()
super(ZeroServer, self).__del__(*args, **kwargs)
def validate_token(self, token):
r = self.SaltClient.verify_token(token)
if not r:
r = {"start": '', "token": token, "expire": '', "name": '', "eauth": '', "valid": False}
else:
r['valid'] = True
return r
@zerorpc.stream
def event_stream(self, token):
v = self.validate_token(token)
if v.get('valid', False):
try:
q = GQueue()
self.event_listeners.add(q)
for msg in q:
yield msg
finally:
self.event_listeners.remove(q)
def auth(self, username, password, eauth='pam'):
'''Authenticates a user against external auth and returns a token.'''
def subprocess_auth(msg, q):
from salt.client.api import APIClient
import json
SaltClient = APIClient()
try:
token = SaltClient.create_token(msg)
except:
token = {
'error': 'Invalid credentials',
'details': 'Authentication failed with provided credentials.'
}
q.put(json.dumps(token))
q = GQueue()
msg = {
'username': username,
'password': password,
'eauth': eauth
}
subprocess_auth(msg, q)
token = q.get()
return json.loads(token)
def cmd(self, cmdmesg):
def subprocess_cmd(msg, q):
from salt.client.api import APIClient
import json
SaltClient = APIClient()
u = SaltClient.verify_token(msg['token'])
if not u:
q.put({"error": "Invalid token"})
return
retval = SaltClient.run(msg)
echodict = deepcopy(msg)
echodict.pop('token')
if msg.get('mode', 'async') == 'async':
echodict['minions'] = retval['minions']
echodict['jid'] = retval['jid']
else:
echodict['result'] = retval
echodict['username'] = u['name']
q.put(json.dumps(echodict))
q = GQueue()
subprocess_cmd(cmdmesg, q)
retval = q.get()
return json.loads(retval)
def runner_sync(self, cmdmesg):
def subprocess_runner(msg, q):
from salt.client.api import APIClient
import json
SaltClient = APIClient()
u = SaltClient.verify_token(msg['token'])
if not u:
q.put({"error": "Invalid token"})
return
resp = SaltClient.runnerClient.cmd(cmdmesg['fun'], cmdmesg['arg'])
q.put(json.dumps(resp))
q = GQueue()
subprocess_runner(cmdmesg, q)
retval = q.get()
#.........这里部分代码省略.........
示例8: print
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
print('fork: \nProcess (%s) start...' % os.getpid())
pid = os.fork() # fork 轻松创建子进程
if pid == 0: # 子进程返回 0, 父进程返回子进程的 id, getppid() 得到父进程 pid
print('I am child process (%s) and my parent is (%s).' % (os.getpid(), os.getppid()))
exit(0) # 子进程执行打这里就退出, 不执行后面的
else: print('I (%s) just created a child process (%s).' % (os.getpid(), pid))
##################################################################
## multiprocessing Process
from multiprocessing import Process # fork 无法在 Windows 上运行, Process 可以跨平台
def run_proc(name): print('Run child process %s (%s)...' % (name, os.getpid())) # 子进程要执行的代码
print('\nProcess: \nParent process (%s).' % os.getpid())
p = Process(target=run_proc, args=('test',)) # 参数在 args 中传
p.start() # start() 方法启动, 这样创建进程比 fork() 还要简单
p.join() # join() 方法可以等待子进程结束后再继续往下运行, 通常用于进程间的同步
##################################################################
## subprocess
import subprocess # 启动一个子进程, 然后控制其输入和输出
print('\nsubprocess 没有控制输入输出: \n$ nslookup www.python.org') # 不用控制的
r = subprocess.call(['nslookup', 'www.python.org']); print('Exit code:', r)
print('\nsubprocess 控制输入输出: $ nslookup')
p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b'set q=mx\npython.org\nexit\n') # 相当于下面三条命令: set q=mx; python.org; exit
print(output.decode('utf-8'))
print('Exit code:', p.returncode)
p = subprocess.Popen(['nslookup'], stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
p.wait() # 加上这句话才能在终端等待输入...
p.kill()
print(p.returncode) # 手动结束的话不会执行到这里, 执行到 kill() 后就会报错 KeyboardInterrupt
示例9: xrange
# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import kill [as 别名]
op.error("Invalid port number")
try:
processes = []
for a in xrange(options.count):
try:
w = DesWorker(address, port, options.secret)
except AssertionError as e:
import traceback
traceback.print_exc()
print "Error probably due to key mismatch"
sys.exit()
w.log("Connected to manager at %s:%s" % (address, port))
process = Process(target=w.run)
processes.append(process)
# Start processes and wait
for process in processes:
process.start()
for process in processes:
process.join()
# Always kill all processes when finished
finally:
for process in processes:
try:
process.kill()
except Exception: pass