Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Why do we need sys.argv[1] exactly?

I'm still unsure about the functionality/necessity of this whole area under the
name == 'main': function. Is it just a way to index the contents of the file?

Hey mate, can you add in the code please?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

I would need to see the referenced code to understand how says.argv[1] is being used. In regular use, sys.argv[1] refers to the second word on the command line. argv[0] usually refers to the program name “python”.

Regarding the use of __name__:

Keep in mind that any python file may be imported to any other file. The “if __name__ == "__main__"” idiom is used to tell whether the current file is being executed as the top level module or if has been imported into another Python file.

Each python file has its own namespace to hold variables. The name of the current file is held in this namespace as the variable __name__. However, if the file was invoked using python filename.py then, instead of the filename, the string “__main__” is assigned. So, by using this idiom, the code under this if statement can be restricted to run if and only if the current file was called directly by the python interpreter as the top module.

Post back if you need more help. Good luck!!!