Using python method in other program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alex Frieder
    New Member
    • Dec 2011
    • 1

    Using python method in other program

    I'm new at Python. I created a program that (for example) prints the number.
    So test.py is:

    Code:
    def a(b):
        print b
    Now I have a program use.py and I want to use a() in it. How would I go about importing it (the import() method doesn't work). They're in the same folder on my desktop. I appreciate any help.
    Last edited by bvdet; Dec 16 '11, 10:00 PM. Reason: Add code tags
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi. Welcome to python!

    This is actually one of the strengths of python. This should work:

    Code:
    import test
    test.a("Hello world")
    Or

    Code:
    from test import *
    a("Hello world")
    Or

    Code:
    from test import a
    a("Hello world")
    You will generally have had to run test.py, not just saved it.

    It's quite common practice to have something like this at the bottom of your test.py:
    Code:
    if __name__=="__main__":
        a("Hello world")
    Why? Because if you run test.py, then the above will run also. But if you import test.py then the above will not run. So you can import all the methods without running the test code.

    Hope this helps.

    Comment

    Working...