Python restart program

半腔热情 提交于 2019-12-10 12:25:19

问题


I made a program that asks you at the end for a restart.

I import os and used os.execl(sys.executable, sys.executable, * sys.argv) but nothing happened, why?

Here's the code:

restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
    os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
    print("\nThe program will be closed...")
    sys.exit(0)

回答1:


import os
import sys

restart = input("\nDo you want to restart the program? [y/n] > ")

if restart == "y":
    os.execl(sys.executable, os.path.abspath(__file__), *sys.argv) 
else:
    print("\nThe programm will me closed...")
    sys.exit(0)

os.execl(path, arg0, arg1, ...)

sys.executable: python executeable

os.path.abspath(__file__): the python code file you are running.

*sys.argv: remaining argument

It will execute the program again something like python XX.py arg1 arg2.




回答2:


Maybe os.execv will work but why not use directly using os.system('python "filename.py"') if you have environment and path variable set something like :

import os

print("Hello World!")
result=input("\nDo you want to restart the program? [y/n] > ")
if result=='y':
     os.system('python "C:/Users/Desktop/PYTHON BEST/Hackerrank.py"')
else:
     print("\nThe programm will me closed...")



回答3:


os.execv(sys.executable, ['python'] + sys.argv)

solved the problem.



来源:https://stackoverflow.com/questions/48129942/python-restart-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!