2015-03-02 61 views
1

我想用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的新手,所以我先以我的名義嘗試。請原諒,如果對概念缺乏瞭解

+0

你輸入錯誤:只是'import Script1' – ForceBru 2015-03-02 19:04:19

+0

@ForceBru這是一個錯字。感謝您的注意! – 2015-03-02 19:06:32

+0

它看起來像一個緩衝問題。 [運行'-u'選項來強制緩衝輸出(主進程和子進程)或者只是定義'PYTHONUNBUFFERED' envvar](http://stackoverflow.com/q/107705/4279) – jfs 2015-03-02 19:11:03

回答

1

子進程調用外部程序。您的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() 
+0

是否有可能通過'subprocess'完成它,因爲它是在應用程序中使其具有通用性的要求? – 2015-03-02 19:18:13

+0

你應該在末尾加上'if __name __ =='__ main__「:func()'。 – jfs 2015-03-02 19:19:21

+0

@ J.F.Sebastian在我應該提到這個腳本的末尾?我在'Script2.py'的末尾添加了'if __name __ =='__ main__「:',並在'Script1.py'處同樣調用了'sub()',同樣也爲'Script1.py'添加了相同的名稱。另外我怎樣才能從Script2.py函數(子進程)獲取返回值? – 2015-03-02 19:27:41