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
Related
I'm working with/rewriting a code that first defines a function as follows:
def main(argv=[__name__]):
...
*rest of code*
...
and ends with:
if __name__ == "__main__":
sys.exit(main(sys.argv))
I'm under the impression that what this is doing is checking to make sure that the script is being executed from the command line, and then running the function main with the arguments provided as it exits python. But then, why is it necessary to preset the variable argv to [__name__] in the function definition? This is not my code, so I don't know the original intention behind this. I am, however, new to using if __name__ == "__main__": lines to spot check command line execution, so maybe there is some glaringly obvious reason for this syntax that I'm missing. Any help, or further detail on main function definition and argument/command-line-vs-module testing would be appreciated.
As for the argv=[__name__], the original dev probably wanted to keep the option to run this function not from the command line (i.e. invoked by another module), and provided __name__ because it uses sys.argv[0] for some functionality.
The main function is nothing to do with python, just some convention (derived from languages like C). sys.exit(main(sys.argv)) will trigger the sys.exit function with an exit code equivalent to the product of running the main function with the received command line arguments. main probably should return an appropriate exit code (0 is to indicate OK, others imply various exceptions).
The main() definition allows for the possibility that main() will be called in other ways than the sys.exit() line at the bottom of the file. This might be an example of defensive programming, or it might indicate other supported uses of this file.
One such other supported use might be to invoke it from another Python program, like so:
import your_module
your_module.main()
When a script is run from the CLI, argv[0] is the name of the script, and the rest of argv is the command-line arguments. So the rest of main() may expect that argv[0] will always be filled in.
The default value is ensuring that argv[0] has something analogous in it when the file is being imported instead of being run directly. In this case, it's the name of the module.
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.
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.
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 written a script that is pretty temperamental with indentation, so I decided to make functions. I'm pretty new to Python and now that I've created these functions, nothing works!
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
I'm just wondering if this is the correct way to call functions from the main() function? I've been debating if an indentation issue is occurring within the called functions. Python seems to be very reliant on proper indentations even though it doesn't come up with an error!
Full Code - http://pastebin.com/gJGdHLgr
It sounds like you need to do this:
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
main() # This calls your main function
Even better:
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
if __name__ == '__main__':
main() # This calls your main function
Then run it from the command line like this:
python file_name.py
The built-in variable __name__ is the current contextual namespace. If you run a script from the command line, it will be equivalent to '__main__'. If you run/import the .py file as a module from somewhere else, including from inside the interpreter, the namespace (inside of the context of the module) will be the .py file name, or the package name if it is part of a package. For example:
## File my_file.py ##
print('__name__ is {0}'.format(__name__))
if __name__ = '__main__':
print("Hello, World!")
If you do this from command line:
python my_file.py
You will get:
__name__ is __main__
Hello, World!
If you import it from the interpreter, however, you can see that __name__ is not __main__:
>>> from my_file import *
>>> __name__ is my_file
Python doesn't call any functions on starting unless explicitly asked to (including main).
Instead Python names the files being run, with the main file being run called __main__.
If you want to simply call the main function you can use Rick's answer.
However in Python best practice it is better to do the following:
if __name__ == '__main__':
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
This ensures that if you are running this Python file as the main file (the file you click on, or run from the command line then these functions will be run.
If this is instead used as an imported module, you can still use the functions in the script importing the module, but they will not be called automatically and thus won't interfere with the calling script.
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.)