如何从主方法自动启动程序

0 投票
3 回答
17098 浏览
提问于 2025-04-16 11:38

这是我的代码

def main():
    # This code reads in data.txt and loads it into an array
    # Array will be used to add friends, remove and list
    # when we quit, we'll overwrite original friends.txt with
    # contents 

    print"Welcome to the program"

    print "Enter the correct number"
    print "Hockey fan 1, basketball fan 2, cricket fan 3"
    choice = input("Select an option")

    while choice!=3:
        if choice==1:
            addString = raw_input("Who is your favorite player??")
            print "I love Kessel"
        elif choice==2:
            remInt = raw_input("Do you think that the Cavaliers will continue ther loosing ways?")
            print "I think they can beat the Clippers"
        else:
             "You must choose a Number (1,2 or 3)"
    print "Cricket is a great sport"
    choice = input("Select an option")



    inFile = open('data.txt','r')
    listNumbers = []
    for numbers in inFile:
        listNumbers.append(numbers)
        print numbers
    inFile.close()

if __name__ == "__main__":
    main() # will call the 'main' function only when you execute this from the command line.

3 个回答

3

你可以试试下面的方法:

if __name__ == "__main__":
    main()

完成这些后,你可以在命令行中这样运行你的程序(假设你是在Linux或Mac上):

python <your_prog>

另外,如果你能提供你遇到的具体错误信息,那会很有帮助。确保所有的缩进都是正确的。

4

在文件的末尾添加:

if __name__ == "__main__":
    main()

12

添加:

if __name__ == "__main__":
    main()

把它放到你的脚本里(要完全靠左对齐,不要放在main()函数里面)。

撰写回答