【发布时间】:2015-05-03 06:13:57
【问题描述】:
我正在尝试使用 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 启动第一个进程的脚本,然后稍后也启动子进程
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 编写的打印语句,并且它在主进程完成后停止。此外,我不确定从子流程中获取 return 语句值的方式。任何人都可以帮助我尝试获得正确的输出。
注意:我是 python 和子进程的新手,所以我先代表我尝试。对概念有不理解的地方还请见谅
【问题讨论】:
-
你导入错误:只是
import Script1 -
@ForceBru 这是一个错字。感谢您的关注!
-
@J.F.Sebastian 我认为它没有进入子进程脚本(Script2.py),因为我没有看到该脚本中的任何打印语句。 Script1.py 执行结束后也停止执行。
-
@J.F.Sebastian 我应该在哪里以及如何提及
-u选项?
标签: python subprocess