[python]python学习笔记(四)

时间:2022-05-10 19:19:01

14,python如何创建进程并在父子进程通信
示例代码如下:

import os, sys
print "I'm going to fork now - the child will write something to a pipe, and the parent will read it back"
r, w = os.pipe() # r,w是文件描述符, 不是文件对象
pid = os.fork()
if pid:
# 父进程
os.close(w) # 关闭一个文件描述符
r = os.fdopen(r) # 将r转化为文件对象
print "parent: reading"
txt = r.read()
os.waitpid(pid, 0) # 确保子进程被撤销
else:
# 子进程
os.close(r)
w = os.fdopen(w, 'w')
print "child: writing"
w.write("here's some text from the child")
w.close()
print "child: closing"
sys.exit(0)
print "parent: got it; text =", txt


 15 py2exe

点击打开链接

 

16,python如何判断当前操作系统的类型:

def UsePlatform():
  sysstr = platform.system()
  if(sysstr =="Windows"):
    print ("Call Windows tasks")
  elif(sysstr == "Linux"):
    print ("Call Linux tasks")
  else:
    print ("Other System tasks")

 

17,python文件夹复制:

以下转自:http://www.oschina.net/code/snippet_16840_1654

sourceDir = r"\\192.168.3.250\mmtimages"   

10 targetDir = r"D:\mmtimages"

11 copyFileCounts = 0

12

13 def copyFiles(sourceDir, targetDir):

14 global copyFileCounts

15 print sourceDir

16 print u"%s 当前处理文件夹%s已处理%s 个文件" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sourceDir,copyFileCounts)

17 for f in os.listdir(sourceDir):

18 sourceF = os.path.join(sourceDir, f)

19 targetF = os.path.join(targetDir, f)

20

21 if os.path.isfile(sourceF):

22 #创建目录

23 if not os.path.exists(targetDir):

24 os.makedirs(targetDir)

25 copyFileCounts += 1

26

27 #文件不存在,或者存在但是大小不同,覆盖

28 if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):

29 #2进制文件

30 open(targetF, "wb").write(open(sourceF, "rb").read())

31 print u"%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)

32 else:

33 print u"%s %s 已存在,不重复复制" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)

34

35 if os.path.isdir(sourceF):

36 copyFiles(sourceF, targetF)