#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    62
    Rep Power
    10

    Execute just some portion of code if imported...


    Hi guys, it's been a while.
    I have 2 scripts, and one of then gets imported in the other. When the first script is imported, how can I make only a portion of it to be executed, and not the whole thing?
    In pseudo code (not python):
    imported script:
    Code:
    if imported:
      execute code
    if not:
      execute another code
    Can this be done?
    How is this topic called?
    Thank you...
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4248
    Like this perhaps?
    python Code:
     
    def func1():
        print "function1"
     
    def func2():
        print "function2"
     
    if __name__ == "__main__":
        func1()
    else:
        func2()

    When run by itself, __name__ will equal "__main__" and hence it will execute func1(). When imported as a module, it will execute func2()
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    62
    Rep Power
    10
    Ok, that was it. Many thanks!
    dan

IMN logo majestic logo threadwatch logo seochat tools logo