The main () function does not start when the script starts

#! /usr/bin/python def main(): print("boo") 

This code does nothing when I try to run it in Python 3.3. No mistake or anything else. What happened

 [ tim@tim-arch ~]$ gvim script [ tim@tim-arch ~]$ sudo chmod 775 script [ tim@tim-arch ~]$ ./script [ tim@tim-arch ~]$ 
+4
source share
4 answers

You still need 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 
+28
source

I assume that you want to make a print function call when the script is executed from the command line.

In python, you can find out if the script containing the piece of code is the same as the script that was run initially by checking the __name__ variable for __main__ .

 #! /usr/bin/python if __name__ == '__main__': print("boo") 

Only with these lines of code:

 def main(): print("boo") 

you define a function and do not call it at all. To call the main() function, you need to call it like this:

 main() 
+13
source

You need to call these functions, update the script to

 #! /usr/bin/python def main(): print("boo") #call it main() 
+4
source

In python, if you want to write a script for sequentially executing a series of small tasks, then there is absolutely no to write a function to store them. Just put each on a line yourself; or use an expression delimiter, for example ; (not recommended, but you can do it like this), as well as:

 task1 task2 task3 task4 

or

 task1; task2; task3; (again **not** really recommended, and certainly not pythonic) 

In your case, your code may be facing something like:

 print('boo') print('boo2') print('boo3') 

and it will still act as you expect, without the main() method, since they will be evaluated sequentially.

Please note that the reason you can create a function for these series of tasks is:

  • to present a nice interface (for code clients),
  • or encapsulate repeating logic
  • There may be more uses, but the first thing I can come up with and serve to prove my point.

Now, if you are forced to write code similar to the main() method in other programming languages, please use the following python idiom (as indicated by other users so far):

 if __name__ == '__main__': doSomething() 

The above works as follows:

  • When you import a python module, it gets the string (usually the name under which it was imported) assigned as its __name__ attribute.
  • When the script is executed directly (by calling python vm and passing the script name as an argument), the __name__ attribute has the value __main__
  • Therefore, when you use the above idiom, you can use the script as an import plugin as you wish, or simply execute it directly to have a series of expressions under if __name__ == '__main__': evaluated directly.

If you feel the need to dig out additional information, my sources were as follows:

+2
source

All Articles