4

我制作了一个程序,最后要求您重新启动。

import os和用过os.execl(sys.executable, sys.executable, * sys.argv) 但什么也没发生,为什么?

这是代码:

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)
4

4 回答 4

6
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(路径,arg0,arg1,...)

sys.executable: python 可执行

os.path.abspath(__file__):你正在运行的python代码文件。

*sys.argv: 剩余参数

它将再次执行程序,例如python XX.py arg1 arg2.

于 2018-01-06T17:50:33.853 回答
3

os.system('python "filename.py"')也许 os.execv 会起作用,但如果你设置了环境和路径变量,为什么不直接使用 using :

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 program will be closed...")
于 2018-01-06T18:10:37.773 回答
1

只需导入您要重新启动的程序并在所需条件下运行它,如标题:你好。py import hello If(在此处输入一般条件):你好

于 2021-11-28T23:46:01.863 回答
-3
os.execv(sys.executable, ['python'] + sys.argv)

解决了这个问题。

于 2018-01-06T18:01:48.520 回答