Python main function not working [duplicate]

2019-02-26 06:27发布

问题:

This question already has an answer here:

  • main() function doesn't run when running script 5 answers

I am writing a simple Python program with some functions, one of which is a main() function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?

def print1():
    print("this is also a function")
def print2():
    print("this is a function")

def main():
    print1()
    print2()

回答1:

You need to call main(). Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?

def print1():
    print("this is also a function")
def print2():
    print("this is a function")

def main():
    print1()
    print2()

main()

It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the __name__ variable is set either to '__main__' or the name of the file. It is set to '__main__' if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:

if __name__ == '__main__':
    main()

That way, you can import the module, and use the functions without main() being called. If it is run as a python script, however, main() will be called.



回答2:

You need to call main() in order for it to run.



回答3:

I believe what you mean to be doing is

def print1():
    print("this is also a function")
def print2():
    print("this is a function")

if __name__ == '__main__':
    print1()
    print2()

Call this script something.py and then run python something.py from your command line.



回答4:

Add this to the bottom of your code.

if __name__ == "__main__":
    main()

See https://docs.python.org/2/library/main.html

Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.

You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.