andylin02 发表于 2013-2-7 09:58:33

python之subprocess 创建子进程



<div class="blogstory">ps:实现代码
#!/usr/bin/env pythonimport subprocess;def run_proc1(strProc):    proc = subprocess.Popen(strProc, shell = False);    #proc.stdin.write('a');    #proc.stdin.write('b');def run_proc2(lsProc):    subprocess.call(lsProc);if "__main__" == __name__:    print("start exec a child process");    run_proc1('./hello.exe');    #run_proc2(['./hello.exe', '-a', '-b', '-c']);    print("end of exec");  
  最近,我们老大要我写一个守护者程序,对服务器进程进行守护。如果服务器不幸挂掉了,守护者能即时的重启应用程序。上网Google了一下,发现Python有很几个模块都可以创建进程。最终我选择使用subprocess模块,因为在Python手册中有这样一段话:
  This module intends to replace several other, older modules andfunctions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*
  subprocess被用来替换一些老的模块和函数,如:os.system、os.spawn*、os.popen*、popen2.*、commands.*。可见,subprocess是被推荐使用的模块。
下面是一个很简单的例子,创建一个新进程,执行app1.exe,传入相当的参数,并打印出进程的返回值:
<div class="dp-highlighter nogutter">
[*]import subprocess  
[*]  
[*]returnCode = subprocess.call('app1.exe -a -b -c -d')  
[*]print 'returncode:', returnCode  
[*]  
[*]#----- 结果 --------  
[*]#Python is powerful  
[*]#app1.exe  
[*]#-a  
[*]#-b  
[*]#-c  
[*]#-d  
[*]returncode: 0  
页: [1]
查看完整版本: python之subprocess 创建子进程