Why do some python scripts declare main() in this manner? [duplicate] - python

This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 6 years ago.
In some python scripts, I see this format;
def main():
#run code
if __name__ == "__main__":
main()
In other python scripts, the line if __name__ == "__main__": is not present but the code runs normally. Why have this extra redundant line when the code can run normally even without it? What is the advantage of using if __name__ == "__main__":?

This line allows you to make some functionality run by default only when you run the script as the main script (e.g. python my_script.py).
This is useful when the script may be used either as a main program or to be imported in another python module, or python shell. In the latter case you would almost certainly not want main (or other module functionality) to run on import, which is what happens by default when the interpreter loads a script.
If you'll never import this script in other code, or in a python shell then you don't need this line. However, it's good to design your code to be modular & import friendly; even what may appear as throw away scripts (e.g. plotting some numbers, parsing some logs etc.) may be useful in a larger context. Particularly in an interactive shell session, e.g. using ipython. And the cost is small: encapsulate statements in functions and add ifmain.

That is usefull when you are making a module or in general if you intend to import your scipt when running an other script. __name__ == "__main__" is true only when that script is the main script that is executed , so it avoids running subsequent code when it is ran at an import statement.

Related

Call a python script from a python script within the same context

There is a python script start_test.py.
There is a second python script siple_test.py.
# pseudo code:
start_test.py --calls--> subprocess(python.exe simple_test.py, args_simple_test[])
The python interpreter for both scripts is the same. So instead of opening a new instance, I want to run simple_test.py directly from start_test.py. I need to preserve the sys.args environment. A nice to have would be to actually enter following code section in simple_test.py:
# file: simple_test.py
if __name__ == '__main__':
some_test_function()
Most important is, that the way should be a universal one, not depending on the content of the simple_test.py.
This setup would provide two benefits:
The call is much less resource intensive
The whole stack of simple_test.py can be debugged with pycharm
So, how do I execute the call of a python script, from a python script, without starting a new subprocess?
"Executing a script" is a somewhat blurry term.
Typically the if __name__== "__main__": part does the argument (sys.argv) decoding and then calls a worker function with explicit parameters. For clarity: It should not do anything else, since this additional work can't be called without creating a new process causing all the overhead you are trying to avoid.
You simply bypass that and call this implementing routine directly.
So you end up with start_test.py containing something like:
from simple_test import worker
# ...
worker(typed_arg1, typed_arg2)

Why doesn't IDLE need 'if __name__ == "__main__": to run a test case, but PyCharm does?

I'm practicing working with unittest, and I tried the following in PyCharm:
import unittest
from format_name import name_formatted
class TestName_formatted(unittest.TestCase):
"""practice with unittest"""
def test_name(self):
"""Testing name_formatted function"""
formatted_name = name_formatted("mike", "Cronin")
self.assertEqual(formatted_name, "mike Cronin")
unittest.main()
After research, I saw that it was written like this:
if __name__ == "__main__":
unittest.main()
And suddenly it worked perfectly. HOWEVER, the reason I wrote it that way, without the if statement, is because that's how I learned it from "Python Crash Course" which uses GEANY and IDLE for its example code. And sure enough, in both of those programs, you don't need the if statement.
Why is it that in one IDE the code doesn't work and in the others it does?
You are running the code in PyCharm as if it were a normal Python application; which is why you need the if __name__ == '__main__' conditional. This is also best practice when writing modules (files) that can be imported or run at the command line - the case with unit tests.
PyCharm is basically trying to do python your_file_name.py
The reason IDLE doesn't need this is because IDLE is running the application by first loading the file in the Python shell.
What IDLE is doing is:
python
>>> import your_file_name
By doing so, the code is automatically evaluated, the function is called and thus the test runs.
I would also suggest reading the documentation on testing in PyCharm's manual as testing is something PyCharm has extensive support for. In that link you'll also notice the default stub (or template) for a sample test case already has the if __name__ == '__main__' check:

Python: use main function [duplicate]

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 have code with many functions and main, when I am trying to run the code it's not working and showing like it run successfully. When I am run the debugger it's show me that it run only on the functions' names. so I am pretty sure the problem it's with the main. how can i solve it?
main() is not run implicitly (like in C or Java). In Python you have to explicitly call if you want your code to run.
def main():
some_code()
if __name__ == "__main__":
main() # actually run main
Note that main does not have to be named main - it may be arbitrary named function. Moreover, code to run does not even have to be enclosed in any function. Consider file with content like that:
print "abc"
It'll simply print "abc" on standard output.

main() function doesn't run when running script [duplicate]

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 5 months ago.
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
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
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()
You need to call that function. Update the script to:
#! /usr/bin/python
def main():
print("boo")
# Call it
main()
In Python, if you want to write a script to perform a series of small tasks sequentially, then there is absolutely no need to write a function to contain them.
Just put each on a line on its own; or use an expression delimiter like ; (not really recommended, but you can do is you so desire), likewise:
task1
task2
task3
task4
or
task1; task2; task3; (again **not** really recommended, and certainly not pythonic)
In your case your code could be turned to something like:
print('boo')
print('boo2')
print('boo3')
and it would still act as you expect it to, without the main() method, as they get evaluated sequentially.
Please note that the reason you might want to create a function for these series of tasks is:
to present a nice interface (to clients of the code),
or to encapsulate repeated logic
There might be more uses, but that's the first I can come up with, and serve to prove my point.
Now, if you feel compelled to write code that resembles the main() method in other programming languages, then please use the following Python idiom (as stated by other users so far):
if __name__ == '__main__':
doSomething()
The above is working as follows:
When you import a Python module, it gets a string (usually, the name under which it was imported) assigned as its __name__ attribute.
When you execute a script directly (by invoking the Python vm and passing it the script's name as an argument), the __name__ attribute is set to __main__
So when you use the above idiom, you can both use the script as a pluggable module by importing it at will, or just execute it directly to have the series of expressions under the if __name__ == '__main__': be evaluated directly.
Should you feel the need to dig through more information, my sources were the following:
Python documentation: Modules
Python documentation: Executing modules as scripts
Python documentation: The data model (search for __name__)
If you find the other answers confusing or intimidating, here's a parable which should hopefully help. Look at the following Python program:
a = 34
When it runs, it does something: before exiting the script, Python learns that there is a variable a and that its value is the integer 34. It doesn't do anything with this information, but it's a complete program which does something. In order for it to produce some actual value, it needs to interact with its environment, though. What does it do with this value? It could create 34 directories, or ping the 34th server in your data center, or check the strength of the passwords of the newest 34 users in your database, or whatever; or just print something.
a = 34
print(a)
The following program is in some sense very similar to the first one.
def b():
a = 34
print(a)
When you run this program, it does something: Python now knows that there is a function named b, and that it doesn't take any arguments, and that it contains some syntactically valid Python code which will be run when some other code calls it, but it doesn't actually do anything with this code yet. In order to observe any value being produced by the code in the function, you have to actually call it:
b()
(As an aside, maybe also note that the local variable a inside the function declaration b is distinct from the global variable with the same name.)

How to run python functions in unix? [duplicate]

This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 5 months ago.
Whenever I tried to run my python script in unix nothing would happen. I'd type something along the lines
$ python script.py
and all that would be returned is
$
Now I know it isn't a problem in my code because that runs fine in idle, so I figured I needed to add something else to my code to be able to run it from the command line. In a google tutorial on python I was introduced to boilerplate code which is tacked onto the end of a function as such
def main():
print ...
etc etc
if __name__ == '__main__':
main()
And if I write a function called main and run it just like that it works fine. However when I named my function something else, anything else, it won't work. E.g.
def merge():
print ..
etc etc
if __name__ == '__merge__':
merge()
That function won't produce any output at all on the command line
Even if I just went and removed the n from the end of word main, each time it occurs in the main function above, it won't work. How does one make python functions run on the command line? and what the heck is up with python only letting functions called main be run?
Thanks!
When you run a python script from the command line, __name__ is always '__main__'.
Try something like:
def merge():
print ..
etc etc
if __name__ == '__main__':
merge()
From the Python interpreter, you have to do something more like:
>>> import script
>>> script.merge()
__name__ == "__main__"
should not be changed, if you run code from the same file you have your functions on
if __name__ == "__main__":
merge()
don't bother about that if only you're importing that module within another file
This link explains you a bith more

Categories

Resources