使用子进程同时执行两个进程的问题
我想用subprocess
从python脚本内执行python脚本,但我遇到了一些问题。这里是我想要做的:使用子进程同时执行两个进程的问题
我想先启动一个主进程(执行python脚本1),并在一段时间后执行此进程,我想启动一个子进程(执行python脚本2)。现在,虽然这个子进程正在执行,但我仍然认为主进程的执行也会继续,当主进程结束时它应该等待子进程完成。
下面是我写的代码。这里Script1.py
是我导入到我的代码中的主要进程脚本。 Script2.py
是使用subprocess.Popen()
调用的子流程脚本。
Script1.py
import time
def func():
print "Start time : %s" % time.ctime()
time.sleep(2)
print "End time: %s" % time.ctime()
return 'main process'
Script2.py
import time
def sub():
count=0
while count < 5:
print "Start time : %s" % time.ctime()
time.sleep(3)
print "End time: %s" % time.ctime()
x+=1
return 'sub process'
if __name__ == '__main__':
print 'calling function inside sub process'
subval = sub()
Main_File.py是通过导入Script1.py
,然后也开始子进程后启动的第一个程序脚本on
Main _file.py
import subprocess
import sys
import Script1
def func1():
count=0
while x < 5:
code = Script1.func()
if x == 2:
print 'calling subprocess'
sub_result = subprocess.Popen([sys.executable,"./Script2.py"]) # Start the execution of sub process. Main process should keep on executing simultaneously
x+=1
print 'Main process done'
sub_result.wait() # even though main process is done it should wait for sub process to get over
code = sub_result # Get the value of return statement from Sub process
return code
if __name__ == '__main__':
print 'starting main process'
return_stat = func1()
print return_stat
当我运行Main_file.py
则执行输出是不正确的。看起来它没有执行子进程,因为我没有看到任何用Script2.py写的print语句,并且在主进程完成后停止。此外,我不确定从子流程获取返回语句值的方式。任何人都可以帮助我尝试实现正确的输出。
注意:我是python和subprocess的新手,所以我先以我的名义尝试。请原谅,如果对概念缺乏了解
子进程调用外部程序。您的Script2不执行任何操作,因为函数sub
未被调用。也许你想要使用线程:
import threading
import Script1
import Script2
def func():
thread1 = threading.Thread(target=Script1.func)
thread1.start()
thread2 = threading.Thread(target=Script2.sub)
thread2.start()
thread2.wait()
是否有可能通过'subprocess'完成它,因为它是在应用程序中使其具有通用性的要求? – 2015-03-02 19:18:13
你应该在末尾加上'if __name __ =='__ main__“:func()'。 – jfs 2015-03-02 19:19:21
@ J.F.Sebastian在我应该提到这个脚本的末尾?我在'Script2.py'的末尾添加了'if __name __ =='__ main__“:',并在'Script1.py'处同样调用了'sub()',同样也为'Script1.py'添加了相同的名称。另外我怎样才能从Script2.py函数(子进程)获取返回值? – 2015-03-02 19:27:41
你输入错误:只是'import Script1' – ForceBru 2015-03-02 19:04:19
@ForceBru这是一个错字。感谢您的注意! – 2015-03-02 19:06:32
它看起来像一个缓冲问题。 [运行'-u'选项来强制缓冲输出(主进程和子进程)或者只是定义'PYTHONUNBUFFERED' envvar](http://stackoverflow.com/q/107705/4279) – jfs 2015-03-02 19:11:03