如何从内部完全重启我的python脚本?

时间:2015-05-04 06:32:24

标签: python

我正在创建一个小计算器作为项目我希望它在完成时键入yes时重新启动。问题是,我似乎无法弄清楚如何。当谈到python时,我不是一个高手。

   import sys

    OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]

    def userinput():
        while True:
            try:

                number = int(input("Number: "))
                break
            except ValueError:
                print("NOPE...")
        return number

    def operation():
        while True:
            operation = input("Multiply/Divide/Add: ")
            if operation in OPTIONS:
                break
            else:
                print("Not an option.")
        return operation

    def playagain():
        while True:
            again = input("Again? Yes/No: ")
            if again == "Yes" or again == "yes":
                 break
            elif again == "No" or again == "no":
                sys.exit(0)
            else:
                print("Nope..")

    def multiply(x,y):
        z = x * y
        print(z)

    def divide(x,y):
        z = x / y
        print(z)

    def add(x,y):
        z = x + y
        print(z)

    def subtract(x,y):
        z = x - y
        print(z)

    while True:

        operation = operation()
        x = userinput()
        y = userinput()
        if operation == "add" or operation == "Add":
            add(x,y)
        elif operation == "divide" or operation == "Divide":
            divide(x,y)
        elif operation == "multiply" or operation == "Multiply":
            multiply(x,y)
        elif operation == "subtract" or operation == "Subtract":
            subtract(x,y)

        playagain()

我目前在第28行中断,因为我无法找到如何重新启动它。如果有人能帮助我,谢谢!

3 个答案:

答案 0 :(得分:2)

您不需要重新启动脚本,只需在编码之前对设计进行一些考虑。使用您提供的脚本,此问题有两处更改:

def playagain():

    while True:
        again = input("Again? Yes/No: ")
        if again == "Yes" or again == "yes":
             return True
        elif again == "No" or again == "no":
             return False
        else:
            print("Nope..")

然后,在您致电playagain()的地方,将其更改为:

if not playagain(): break

我想我知道你为什么要重启脚本,你有一个错误。

Python函数就像任何其他对象一样。当你说:

operation = operation()  

operation函数的引用重新分配给函数返回的字符串。因此,第二次在重新启动时调用它会失败:

TypeError: 'str' object is not callable

重新命名operation函数,例如foperation

def fopertion():

然后:

operation = foperation()  

因此,完整的代码变为:

import sys

OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]

def userinput():
    while True:
        try:

            number = int(input("Number: "))
            break
        except ValueError:
            print("NOPE...")
    return number

def foperation():
    while True:
        operation = input("Multiply/Divide/Add: ")
        if operation in OPTIONS:
            break
        else:
            print("Not an option.")
    return operation


def playagain():

    while True:
        again = input("Again? Yes/No: ")
        if again == "Yes" or again == "yes":
             return True
        elif again == "No" or again == "no":
             return False
        else:
            print("Nope..")

def multiply(x,y):
    z = x * y
    print(z)

def divide(x,y):
    z = x / y
    print(z)

def add(x,y):
    z = x + y
    print(z)

def subtract(x,y):
    z = x - y
    print(z)

while True:

    operation = foperation()
    x = userinput()
    y = userinput()
    if operation == "add" or operation == "Add":
        add(x,y)
    elif operation == "divide" or operation == "Divide":
        divide(x,y)
    elif operation == "multiply" or operation == "Multiply":
        multiply(x,y)
    elif operation == "subtract" or operation == "Subtract":
        subtract(x,y)

    if not playagain(): break

我可以对此代码进行许多其他改进,但让我们先让它工作。

答案 1 :(得分:0)

而不是重新启动我创建的脚本,以便您可以永久使用它,只有用户自己可以退出它。我只改变了playagain()和while循环,阅读了解释的注释:

import sys

OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]

# python2 compatibility, you dont need to care about this ;-)
try:
    input = raw_input
except:
    pass

def userinput():
    while True:
        try:

            number = int(input("Number: "))
            break
        except ValueError:
            print("NOPE...")
    return number

def operation():
    while True:
        operation = input("Multiply/Divide/Add: ")
        if operation in OPTIONS:
            break
        else:
            print("Not an option.")
    return operation

def playagain():
    """
    return True if userinput "Yes" and False if userinput "no"
    does this until user input is yes or no
    """
    again = input("Again? Yes/No: ")
    if again.lower() == "yes":
        return True
    elif again.lower() == "no":
        return False
    else:
        # reruns the code --> until user input is 'yes' or 'no'
        return playagain()

def multiply(x,y):
    z = x * y
    print(z)

def divide(x,y):
    z = x / y
    print(z)

def add(x,y):
    z = x + y
    print(z)

def subtract(x,y):
    z = x - y
    print(z)

# a main in python: this will be executed when run as a script
# but not when you import something from this
if __name__ == '__main__':

    play = True
    while play:
        operation = operation()
        x = userinput()
        y = userinput()
        if operation == "add" or operation == "Add":
            add(x,y)
        elif operation == "divide" or operation == "Divide":
            divide(x,y)
        elif operation == "multiply" or operation == "Multiply":
            multiply(x,y)
        elif operation == "subtract" or operation == "Subtract":
            subtract(x,y)

        # player/user can exit the loop if he enters "no" and therefore end the loop
        play = playagain()

答案 2 :(得分:-3)

使用os.execv()....

Restarting a Python Script Within Itself