如何在不重新执行整个脚本的情况下再次运行main
?
import sys #importing module that is used to exit the script
def main ():
#doing stuff
main ()
#Re-run the script - looking for a cleaner way to do this!
def restart ():
restart = input("Press any key + Enter to start again, or x + Enter to exit.")
if(restart != "x"):
exec(open("./calc.py").read())
# not sure how to run main() again without calling out the script name again?
else:
print ("Exiting!")
sys.exit ((main))
restart ()
#End of Program
答案 0 :(得分:0)
您可以按顺序直接调用main
,多次重复运行main()
模块方法:
def main( ):
# Code goes here...
return;
main();
main();
main();
但是,如果您希望像重启方法一样进行用户交互,则可能需要考虑使用可选参数(具有默认值的参数)定义main
,以控制是否要求重新运行方法与否。
def main( argv, AskRestart= True ):
# Main code goes here....
if ( AskRestart ):
# User interaction code goes here ...
return;
此外,您可以查看Python 3.5.1中的atexit
包,了解如何在退出解释器时指定要运行的方法:
https://docs.python.org/3.5/library/atexit.html
这将允许您做任何您想做的事情,然后当一切都完成后,让某人选择重新启动整个模块。这将消除对exec
调用的依赖,并且是获得完全相同的预期功能的更连贯和更简单的方法。
答案 1 :(得分:0)
除了Tommy的好建议之外,(我不确定你的目标是不断重启main(),因为main是一个空功能,但它还没有做任何事情,但是...... )在用户输入x
之前,主要不断重复的一种方法可能是使用while True
循环:
import sys #importing module that is used to exit the script
def main ():
#doing stuff
restart() # <-- use main to restart()
#Re-run the script - looking for a cleaner way to do this!
def restart ():
restart = raw_input("Press any key + Enter to start again, or x + Enter to exit.")
while True: # <-- key to continually restart main() function
if(restart != "x"):
exec(open("./calc.py").read())
# not sure how to run main() again without calling out the script name again?
main() # <-- restart main
else:
print ("Exiting!")
sys.exit ((main))
restart ()
#End of Program
希望这也有帮助!