1.求一个python程序,可以输出至少15行的完美杨辉三角一直没把 爱问
NUM = 15def printLine(lineList): lineList = [str(tmpNum) for tmpNum in lineList] #print lineList #print("%s%s" % (" " * (NUM - len(lineList)), " "。
join(lineList))) print " "。join(lineList)。
center(100) #关键是这个地方的输出对齐 我是指定了100的长度的居中对齐for i in range(NUM): if i yhList = [1] * (i 1) else: yhList[1:-1] = [(tmpNum yhList[j]) for j, tmpNum in enumerate(yhList[1:])] printLine(yhList)。
2.谁能介绍下python进程操作吗?
使用process Process在multiproccessing包中,功能是创建进程,包含的方法主要有:is_alive()、join([timeout])、run()、start()、terminate()。
其中,Process以start()启动某个进程 #!/usr/bin/python #coding:utf-8 import os from multiprocessing import Process def domyprocess(msg): print 'process id is %d ' % os.getpid() return if __name__ == '__main__': print 'paraent proccess id %s' % os.getpid() t1 = Process(target=domyprocess,args=('hello',)) t1.start() t1.join() t2 = Process(target=domyprocess,args=('world',)) t2.start() t2.join() 运行结果: paraent proccess id 27616 process id is 27621 process id is 27622。
3.python queue中 task
consumer.run if data == 2 的else分支少了 self.q.task_done()。加上就正常了。
#!/usr/bin/env python3
# coding=utf-8
"""
module/program document
"""
from queue import Queue
from threading import Thread
class producer(Thread):
def __init__(self ,q):
super().__init__()
self.q = q
def run(self):
self.count=5
while self.count>0:
if self.count==1:
self.count -=1
self.q.put(2)
else:
self.count -=1
self.q.put(1)
class consumer(Thread):
def __init__(self,q):
super().__init__()
self.q = q
def run(self):
while True:
data = self.q.get()
if data==2:
print("stop because data=",data)
self.q.task_done()
break
else:
print("data is good,data=",data)
self.q.task_done()
def main():
qq = Queue()
p = producer(qq)
c = consumer(qq)
p.setDaemon(True)
c.setDaemon(True)
p.start()
c.start()
qq.join()
print("queue is complete")
if __name__ == '__main__':
main()
4.python 两个脚本同时执行,并且 互相通信
import sys, threading, queue
if sys.version_info.major == 3:
def execfile(filename, globals=None, locals=None):
g = globals if globals is not None else __builtins__.globals()
l = locals if locals is not None else __builtins__.locals()
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, g, l)
if __name__ == '__main__':
f1 = '/path/to/file1.py' # MainThread
f2 = '/path/to/file2.py'
# 将需要共享的变量放入全局变量字典,在f1和f2中可以直接使用q1和q2两个队列
# f1向f2发送消息:
# f1: q1.put(something)
# f2: q1.get()
# f2向f1发送消息:
# f2: q2.put(something)
# f1: q2.get()
g = {'q1': queue.Queue(), 'q2': queue.Queue()}
g.update(globals())
thread = threading.Thread(target=execfile, args=(f2, ), kwargs={'globals':g})
thread.start()
execfile(f1, globals=g)
thread.join()
转载请注明出处代码入门网 » pythonqueue.join(求一个python程序,可以输出至少15行的完美杨辉三角一直没把爱问)