This is one of my first programs in Python, so I might be missing something obvious.
In this first part of my code that I've posted, I'd like to make sure the user passes a command line argument. If not, I want to show an error and return 1. When I run the code without a command line argument, the program has the expected behavior because the error prints and the program exits.
However, when I run a checker on this, I get an error:
handles lack of argv[1]. expected exit code 1, not 0.
Any ideas on what I may be missing?
import sys
import cs50
from cs50 import get_string
def main(argv):
# Check for command line argument
if (len(sys.argv) != 2):
print("Error: Please input numeric key in command line.")
return 1
if __name__ == "__main__":
main(sys.argv)
In a blog post, Guido van Rossum, the creator of Python, suggests writing the if __name__ == "__main__" block like this:
if __name__ == "__main__":
sys.exit(main())
This way, main() can return a value, like a normal function, and it will be used as an exit code for the process.
I suggest reading the rest of that blog post. It contains helpful suggestions for setting up Python main() function boilerplate to be more flexible.
Related
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.
I have this code:
import sys
def random(size=16):
return open(r"C:\Users\ravishankarv\Documents\Python\key.txt").read(size)
def main():
key = random(13)
print(key)
When I try running the script, there are no errors, but nothing appears to happen. I expected it to print some content from the key file, but nothing is printed.
What is wrong? How do I make the code run?
You've not called your main function at all, so the Python interpreter won't call it for you.
Add this as the last line to just have it called at all times:
main()
Or, if you use the commonly seen:
if __name__ == "__main__":
main()
It will make sure your main method is called only if that module is executed as the starting code by the Python interpreter. More about that here: What does if __name__ == "__main__": do?
If you want to know how to write the best possible 'main' function, Guido van Rossum (the creator of Python) wrote about it here.
Python isn't like other languages where it automatically calls the main() function. All you have done is defined your function.
You have to manually call your main function:
main()
Also, you may commonly see this in some code:
if __name__ == '__main__':
main()
There's no such main method in python, what you have to do is:
if __name__ == '__main__':
main()
Something does happen, it just isn't noticeable
Python runs scripts from top to bottom. def is a statement, and it executes when it is encountered, just like any other statement. However, the effect of this is to create the function (and assign it a name), not to call it. Similarly, import is a statement that loads the other module (and makes its code run top to bottom, with its own global-variable context), and assigns it a name.
When the example code runs, therefore, three things happen:
The code for the sys standard library module runs, and then the name sys in our own module's global variables is bound to that module
A function is created from the code for random, and then the name random is bound to that function
A function is created from the code for main, and then the name main is bound to that function
There is nothing to call the functions, so they aren't called. Since they aren't called, the code inside them isn't run - it's only used to create the functions. Since that code doesn't run, the file isn't read and nothing is printed.
There are no "special" function names
Unlike in some other languages, Python does not care that a function is named main, or anything else. It will not be run automatically.
As the Zen of Python says, "Explicit is better than implicit". If we want a function to be called, we have to call it. The only things that run automatically are the things at top level, because those are the instructions we explicitly gave.
The script starts at the top
In many real-world scripts, you may see a line that says if __name__ == '__main__':. This is not "where the script starts". The script runs top to bottom.
Please read What does if __name__ == "__main__": do? to understand the purpose of such an if statement (short version: it makes sure that part of your top-level code is skipped if someone else imports this file as a module). It is not mandatory, and it does not have any kind of special "signalling" purpose to say where the code starts running. It is just a perfectly normal if statement, that is checking a slightly unusual condition. Nothing requires you to use it in a script (aside from wanting to check what it checks), and nothing prevents you from using it more than once. Nothing prevents you from checking whether __name__ is equal to other values, either (it's just... almost certainly useless).
You're not calling the function. Put main() at the bottom of your code.
I have the following structure in code.
In main.py:
def run(parameters):
# do something
In execution.py:
import main
if __name__ = "main":
main.run(parameters)
However, I get the following error - main has no 'run' member.
When I run that code there is no output, because the test in execution.py should be if __name__ == "__main__":. The if-test in your code is never true.
Buy when I fix that problem, main.run() executes as expected, but only if I fix another problem. The function body of run() must consist of more than a comment. You need pass at the very least.
So that is a syntax error, which means that the def statement doesn't actually define the function. Which explains the message.
I am doing a simple project on my Pycharm IDE.
My code is this:
import webbrowser
import time
socialMediaUrls = ["www.google.com","www.edureka.com"]
techUrls = ["www.udacity.com","www.dailymotion.com"]
def open_tabs(url_list):
for element in url_list:
webbrowser.open_new_tab(element)
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
but after running I am getting this message:
C:\Users\adc\AppData\Local\Programs\Python\Python36-32\python.exe
C:/Users/adc/PycharmProjects/untitled1/ur.py
Process finished with exit code 0
And I am getting same message for all my projects. What should I do?
You should call main in that way:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
if __name__ == "__main__":
main()
Also I see that your code contains some other errors. For example, in Python there is False keyword, not false. Lines with open.tab and open_tabs will not work too.
Currently, no instructions are reachable in your script (besides the import statements)
in:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
indentation suggests that you're performing a recursive call (which isn't what you want).
Unindent main() to make sure you execute something in your script.
Or put the instructions of main at zero-indent level outside any procedure (in that case, it is executed even when importing the module, probably not important here)
(note that python programs don't need a main(), this isn't C)
I have this code:
import sys
def random(size=16):
return open(r"C:\Users\ravishankarv\Documents\Python\key.txt").read(size)
def main():
key = random(13)
print(key)
When I try running the script, there are no errors, but nothing appears to happen. I expected it to print some content from the key file, but nothing is printed.
What is wrong? How do I make the code run?
You've not called your main function at all, so the Python interpreter won't call it for you.
Add this as the last line to just have it called at all times:
main()
Or, if you use the commonly seen:
if __name__ == "__main__":
main()
It will make sure your main method is called only if that module is executed as the starting code by the Python interpreter. More about that here: What does if __name__ == "__main__": do?
If you want to know how to write the best possible 'main' function, Guido van Rossum (the creator of Python) wrote about it here.
Python isn't like other languages where it automatically calls the main() function. All you have done is defined your function.
You have to manually call your main function:
main()
Also, you may commonly see this in some code:
if __name__ == '__main__':
main()
There's no such main method in python, what you have to do is:
if __name__ == '__main__':
main()
Something does happen, it just isn't noticeable
Python runs scripts from top to bottom. def is a statement, and it executes when it is encountered, just like any other statement. However, the effect of this is to create the function (and assign it a name), not to call it. Similarly, import is a statement that loads the other module (and makes its code run top to bottom, with its own global-variable context), and assigns it a name.
When the example code runs, therefore, three things happen:
The code for the sys standard library module runs, and then the name sys in our own module's global variables is bound to that module
A function is created from the code for random, and then the name random is bound to that function
A function is created from the code for main, and then the name main is bound to that function
There is nothing to call the functions, so they aren't called. Since they aren't called, the code inside them isn't run - it's only used to create the functions. Since that code doesn't run, the file isn't read and nothing is printed.
There are no "special" function names
Unlike in some other languages, Python does not care that a function is named main, or anything else. It will not be run automatically.
As the Zen of Python says, "Explicit is better than implicit". If we want a function to be called, we have to call it. The only things that run automatically are the things at top level, because those are the instructions we explicitly gave.
The script starts at the top
In many real-world scripts, you may see a line that says if __name__ == '__main__':. This is not "where the script starts". The script runs top to bottom.
Please read What does if __name__ == "__main__": do? to understand the purpose of such an if statement (short version: it makes sure that part of your top-level code is skipped if someone else imports this file as a module). It is not mandatory, and it does not have any kind of special "signalling" purpose to say where the code starts running. It is just a perfectly normal if statement, that is checking a slightly unusual condition. Nothing requires you to use it in a script (aside from wanting to check what it checks), and nothing prevents you from using it more than once. Nothing prevents you from checking whether __name__ is equal to other values, either (it's just... almost certainly useless).
You're not calling the function. Put main() at the bottom of your code.