Python: use main function [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 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.

Related

How to properly import two files within the same pycharm project? [duplicate]

This question already has answers here:
When importing a function it runs the whole script?
(2 answers)
Closed 4 months ago.
First of all, please keep in mind I'm no python expert, barely even beyond a beginner.
I have this project in pycharm with multiple files (simply for easier navigation/orginisation), and in one, I'm trying to link to a defined print in another file using "from FILENAME import DEFNAME". But whenever I run the file, it runs the second file first, when it should be running parts of the first file. It doesn't even just run the imported def from the 2nd file, it starts from the very beginning of it.
I wrote it originally about a month ago and left it since then, I swear it worked fine last time, how can I prevent file1 from automatically running file2 in its entireity first while also still being able to call on a def from it?
(Removing the "import" line in file1 fixes it, but also isn't helpful at all lol)
It's simply the normal behavior of Python. When you import a function from a file it will run the whole file. Let's put it in an example:
First File
print("This will run First")
def modified_print():
print("This will run Third")
print("This will run Second")
Second File
from first_file import modified_print
if __name__ == '__main__':
modified_print()
Result
This will run First
This will run Second
This will run Third
You can refer to this question for more details When importing a function it runs the whole script?

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

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.

loading python functions returns syntax error [duplicate]

This question already has answers here:
Pasting multiple lines into IDLE
(4 answers)
Closed 9 years ago.
I'm getting an error message quoting that I have a syntax error when trying to load my functions.
I can load them one at a time into the IDLE, but when pasting the full script, an error is returned. I believe its to do with the second function calling the first. To test this, the simple code below also returns this error :(.
def hello():
print('Hello there!')
def boo():
hello()
I'm unsure why this happens because the first function is defined before its called in the second. So it should be loaded in memory already shouldn't it?
Thanks for any help you can give. :)
IDLE interactive interpreter can only handle one task at once, you can't do more.
Save the script to a python file (.py extension), and run it.
From the command line:
$ cd /script_path
$ python script_name.py
Or if you want to run it in IDLE:
Ctrl+N - Paste the code - Save - Press F5
Hope this helps!

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