Python os模块进程函数(2)

运行结果:

-> python test4.py Running ps with execlp PID TT STAT TIME COMMAND 1 ?? Ss 0:12.43 /sbin/launchd 42 ?? Ss 0:03.05 /usr/libexec/UserEventAgent (System) 43 ?? Us 0:05.24 /usr/sbin/syslogd ... 481 s000 S+ 0:00.14 -zsh 1803 s001 Ss+ 0:00.49 /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versio 1806 s002 Ss 0:00.10 /bin/zsh -i 2070 s002 R+ 0:00.02 ps ax

os.system的测试代码如下:

#!/usr/bin/python #coding=utf-8 import os def main(): print "Running ps with execlp" os.system("ps ax") print "Done." main()

运行结果如下:

-> python test4.py Running ps with execlp PID TT STAT TIME COMMAND 1 ?? Ss 0:12.71 /sbin/launchd 42 ?? Ss 0:03.11 /usr/libexec/UserEventAgent (System) ... 481 s000 S+ 0:00.14 -zsh 1803 s001 Ss+ 0:00.50 /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versio 1806 s002 Ss 0:00.10 /bin/zsh -i 2113 s002 S+ 0:00.02 /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versio 2114 s002 R+ 0:00.00 ps ax Done.

以上两个例子对比可以看到 exec系列 的调用使得原进程接下的代码都不会运行。

os.wait #! /usr/bin/python #coding=utf-8 import os import sys def child_process(): '''child process''' print 'child process is running' sys.exit(0) # 常用的退出进程 def parent_process(): '''parent process''' print 'parent process is running' print 'waiting for child process' exit_stat = os.wait() # 返回值是一个pid 和退出状态的元组 print "waited child process's PID = %d" % (exit_stat[0]) sys.exit(0) def main(): '''main function''' try: pid = os.fork() if pid > 0: '''parent process''' parent_process() else: child_process() except OSError, e: print os.strerror(e.errno) main()

运行结果:

-> python test4.py parent process is running waiting for child process child process is running waited child process's PID = 2152 总结

本文简单介绍了系统进程相关的 os.system, os.exec, os.fork, os.wait 系统调用。相关的其它调用如:
os.kill, os.ncie, os.popen, os.spawn系列 可以参照官方文档。另外实际上python多进程编程更加推荐 multiprocessing 模块提供的相关功能,将在以后的文章中探究。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7df882364c4e20667acdb188d7c8fa25.html