如何在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()
上述脚本中有三个功能,
copy_folder()
复制文件夹project-one
,并将其另存为project-two
。 modify_file()
修改project-two
中的文件。 trigger()
结合了上述两个步骤。 问题:
手动执行copy_folder()
和modify_file()
,没关系。但执行trigger()
时出现错误,当modify_file()
未完成时看起来copy_folder()
开始运行,那么如何让它们继续执行?
答案 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()