Python main function not working [duplicate] - python

This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
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()

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.

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.

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

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.

Related

Check if a functon runs as an imported module [duplicate]

This question already has answers here:
python: how to tell if file executed as import vs. main script?
(3 answers)
Closed 1 year ago.
Is possible to check within a function if the given function runs within the script or runs as an imported module in another script?
For example:
def func():
if func was imported:
do this
else: # it runs within the script
do that
Rewrite your function like this:
def func():
if __name__ == '__main__':
print("I'm running within this script.")
else:
print("I was imported to another script.")
if __name__ == '__main__':
func()
If you run the current script, you'll get the following output:
./test.py
>>> I'm running within this script.
If you run from test import func; func() you'll get the following:
>>> I was imported to another script.
Every module has a __name__, if it is imported it will be equal to the name of the module, else it will be '__main__' if it is in the script you run
def func():
if __name__ == '__main__':
# Do this
else:
# Do that

Why not place if __name__ == '__main__' at the beginning of the module?

Why is it standard in Python to have the main() function and the if __name__ == '__main__' check at the end of the block of code? It also seems standard for the abstraction of the functions to follow the same pattern upwards. What I mean is that the definition of the function to be executed by main() is above the main() and the definition of the functions inside that are above and so on..
That seems odd because when one opens the module to read the code, it ends up starting with low-level code and moves up to higher level functions. Isn't it hard to grasp what the module is doing that way?
Why not do the alternative? Have the if __name__ check at the top followed by the main() function, and so on. This way, one quickly glances at what the main() function does and understands what the code is about.
You can't call main() before it is defined. And main cannot call other functions before they are defined.
Example 1:
if __name__=='__main__':
main()
def main():
print("Hello")
This will error because main hasn't been defined yet at the point where you try and execute it.
Example 2:
def main():
hello()
if __name__=='__main__':
main()
def hello():
print("Hello")
This will error because main() is executed and tries to call hello before it is defined.
The if __name__=='__main__': which contains the call to main() works best at the end of the file so that everything that it needs has been defined before it is reached.
Where you put the main definition itself is more flexible, but putting it at the end (just before the if __name__=='__main__': block that calls it) makes as much sense as anywhere else.
The purpose of an if __name__ == '__main__': guard is to prevent a module from having side-effects when it's imported.
The fact that it is a module rather than a script implies that it will normally be used by other code importing the definitions from it, not executed directly. So given that, it makes sense that the functions, classes and constants appear first in the source code, since those are what users of the module will be importing (and hence, what they might want to see the source of).
So even if the code guarded by if __name__ == '__main__': doesn't rely on the definitions in the module already having been evaluated (which would be unusual), this part of the code is usually the least important to the users of the module, so it doesn't belong at the start of the file.

What is the entry point of Python program of multiple modules?

I want to understand from which point a Python program starts running. I have previous experience in Java. In Java every program starts from main() function of it's Main class. Knowing this I can determine the execution sequence of other classes or functions of other Classes. I know that in Python I can control program execution sequence by using __name__ like this:
def main():
print("This is the main routine.")
if __name__ == "__main__":
main()
But when we don't use __name__ then what is the starting line of my Python program?
Interpreter starts to interpret file line by line from the beginning.
If it encounters function definition, it adds it into the globals
dict. If it encounters function call, it searches it in globals
dict and executes or fail.
# foo.py
def foo():
print "hello"
foo()
def test()
print "test"
print "global_string"
if __name__ == "__main__":
print "executed"
else:
print "imported"
Output
hello
global_string
executed
Interpreter starts to interpret foo.py line by line from the beginning like first the function definition it adds to globals dict and then it encounters the call to the function foo() and execute it so it prints hello.
After that, it adds test() to global dict but there's no function call to this function so it will not execute the function.
After that print statement will execute will print global_string.
After that, if condition will execute and in this case, it matched and will print executed.

Import function only in another file

So in my file1.py, I have something like:
def run():
# Do something
print "Hi"
Now I want to use function run() in another file.
from file1.py import run
However, when I execute the other file it also prints Hi. How do I suppress this?
Add the print "Hi" in an if __name__ == "__main__" clause.
When python imports modules it executes the code contained in them in order to build the module namespace. If you run the module as the main script the __name__ is going to get assigned to __main__ and the code inside the if clause is going to get executed.
Since you're not running the script as the main script the __name__ gets assigned to the modules __name__ (in this case file1) and as a result this test will not succeed and the print statement is not going to get executed.
def run():
# Do something
if __name__ == "__main__":
print "Hi"
You should include after the functions this:
this runs the program
if main == "name":# before and after 'main' and 'name' there are two under_scores!
print "hi" etc...
if you don't want Hi to be printed, simply delete from your file1.py
if you want Hi to be printed when run() is called, then indent it so that it belongs to the run() function.

Why is the main() function not defined inside the if '__main__'?

You can often see this (variation a):
def main():
do_something()
do_sth_else()
if __name__ == '__main__':
main()
And I am now wondering why not this (variation b):
if __name__ == '__main__':
do_something()
do_sth_else()
Or at least this (variation c):
if __name__ == '__main__':
def main():
do_something()
do_sth_else()
main()
Of course the function calls inside main() might not be function calls, they just represent anything you might want to do in your main() function.
So why do people prefer variation a over the others? Is it just style/feeling or are there some real reasons? If possible, please also link sources.
Why limit your main() function to command line usage only?
By defining a main() function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.
This is because there are two ways of using Python scripts. One from the command line and another when importing it from another script. When you run it from command line, you want to run main() function and when you import it you may not want to run main() function until you need it ( you just want to import main() ).

Categories

Resources