如何在python中执行两个函数?

时间:2017-10-07 06:49:15

标签: python

如何在python中执行两个函数?
例如,
有一个python脚本:
test.py

#!/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()结合了上述两个步骤。
  4. 问题:
    手动执行copy_folder()modify_file(),没关系。但执行trigger()时出现错误,当modify_file()未完成时看起来copy_folder()开始运行,那么如何让它们继续执行?

1 个答案:

答案 0 :(得分:0)

您的代码看起来很好。看起来像竞争条件,在触发修改之前副本没有完成。在使用time.sleep()之前等待1-2秒。

#!/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()