Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main() function doesn't run when running script

Tags:

python

Consider:

#! /usr/bin/python

def main():
    print("boo")

This code does nothing when I try to run it in Python 3.3. No error or anything.

What’s wrong?

gvim script
chmod 775 script
./script
like image 797
Tim Avatar asked Nov 27 '22 21:11

Tim


2 Answers

You still have to call the function.

def main():  # declaring a function just declares it - the code doesn't run
    print("boo")

main()  # here we call the function
like image 111
Volatility Avatar answered Nov 29 '22 13:11

Volatility


I assumed you wanted to call the print function when the script was executed from the command line.

In Python you can figure out if the script containing a piece of code is the same as the script which was launched initially by checking the __name__ variable against __main__.

#! /usr/bin/python

if __name__ == '__main__':
    print("boo")

With just these lines of code:

def main():
    print("boo")

you're defining a function and not actually invoking it. To invoke the function main(), you need to call it like this:

main()
like image 30
Tuxdude Avatar answered Nov 29 '22 14:11

Tuxdude