[Tutor] Opening a Qt .py file from within another python app

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Mar 22 21:02:52 CET 2012

> python fibo.py <arguments>
> the code in the module will be executed, just as if you imported it, but
> with the __name__ set to "__main__". That means that by adding this code at
> the end of your module:
> if __name__ == "__main__":
>     import sys
>     fib(int(sys.argv[1]))
> you can make the file usable as a script as well as an importable module,
> because the code that parses the command line only runs if the module is
> executed as the “main” file:
> $ python fibo.py 50
> If the module is imported, the code is not run:
> ----------------------------------------------------
> Please bare with me, as I had said, I am a total novice. So if I understand
> this, which Is highly unlikely the,  If __name__==__main__, is what makes
> the module run as a stand alone script? Which shouldn't effect
> it's usability as a module which is imported? So why was it, that I
> couldn't get it to run without including that bit in my main python
> program. And I am assuming the line I had mistook to mean the module
> wouldn't run, means instead that the  "name ==main won't run, which
> once again leads to the question, then why would i need to include it to
> make it function??

> Do you see my point. What am i missing here? Some vital piece of the puzzle
> seems to be eluding me.

No everything in a module is run when imported. Usually modules
are just a class and function definitions so nothing actually happens.
Anything you put in a module that is not in a function or class will
run. If you put a print statement in the module that is not in a function
or class, it will print the statement every time you import the module.
That is why the convention is to use the following code to only 
automatically run the module when running the script.

if __name__ == '__main__':
   # this is only true if you are running the script directly
   # by doing something like python myscript.py


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

More information about the Tutor mailing list