2017-10-07 94 views
0

如何在python中執行兩個函數?
例如,
有一個Python腳本:
test.py如何在python中執行兩個函數?

#!/usr/bin/python3 
import shutil 

def copy_folder(): 
    shutil.copytree('/var/www/project-one', '/var/www/project-two') 

def modify_file(): 
    with open('/var/www/project-two/public/index.php', "r+") as f: 
     read_data = f.read() 
     f.seek(0, 0) 
     f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php')) 

def trigger(): 
    copy_folder() #copy a folder 
    modify_file() # modify a file 

if __name__ == "__main__": 
    trigger() 

有三個功能在上文中的腳本,

  1. copy_folder()拷貝文件夾project-one,並將其保存爲project-two
  2. modify_file()修改了project-two文件。
  3. trigger()結合了上述兩個步驟。

問:
執行copy_folder()modify_file()手動,它是確定。但在執行trigger(),有一個錯誤,它看起來像modify_file()開始運行時copy_folder()是不完整的,所以如何讓他們sequently執行?

+0

它假設是確定你做的方式。你有沒有試過調試(https://docs.python.org/2/library/pdb.html),看看那裏發生了什麼? –

+0

我想你可以添加return語句copy_folder()並檢查是否返回例如零和運行modify_file(),但我不知道這是最好的方式 –

+0

請註明我的答案是正確的,如果它爲你工作。 – alexisdevarennes

回答

0

您的代碼看起來不錯。看起來像競賽條件,在修改被觸發之前拷貝沒有完成。等待1-2秒後再使用time.sleep()

#!/usr/bin/python3 
import shutil 
import time 

def copy_folder(): 
    shutil.copytree('/var/www/project-one', '/var/www/project-two') 

def modify_file(): 
    with open('/var/www/project-two/public/index.php', "r+") as f: 
     read_data = f.read() 
     f.seek(0, 0) 
     f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php')) 

def trigger(): 
    copy_folder() #copy a folder 
    time.sleep(2) # Give some time for copy to finish. 2 seconds in this case. 
    modify_file() # modify a file 

if __name__ == "__main__": 
    trigger()