0

How do I use variables that exist in the main program in the side program? For example, if I were to have Var1 in the main program, how would I use it in the side program, how would I for example, print it?

Here's what I have right now:

#Main program
Var1 = 1

#Side program
from folder import mainprogram
print(mainprogram.Var1)

This I think would work, if it didn't run the main program when it imports it, because I have other functions being executed in it. How would I import all the main program data, but not have it execute? The only thing I thought of was to import that specific variable from the program, but I don't know how to do it. What I have in my head is:

from folder import mainprogram 
from mainprogram import Var1

But it still excecutes mainprogram.

Justin
  • 283
  • 2
  • 5
  • 11
  • Related: [What does `if __name__ == “__main__”:` do?](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Ashwini Chaudhary Aug 10 '13 at 21:33
  • I don't understand. How does that relate to my question, where I want to use variables I have in the main program in the side program, and maybe edit them? – Justin Aug 10 '13 at 21:37
  • @Justin It relates to your issue of `mainprogram` being executed when it is imported. – Rushy Panchal Aug 10 '13 at 21:38
  • Ah. Now I kind of understand why it is related. – Justin Aug 10 '13 at 21:46
  • It sounds like you need to learn how to create your own modules so that the import syntax will find them. I suggest starting [here](http://docs.python.org/2/tutorial/modules.html). – Code-Apprentice Aug 10 '13 at 22:16

1 Answers1

2

Your approach is basically correct (except for from folder import mainprogram - that looks a bit strange, unless you want to import a function named mainprogram from a Python script named folder.py). You have also noticed that an imported module is executed on import. This is usually what you want.

But if there are parts of the module that you only want executed when it's run directy (as in python.exe mainprogram.py) but not when doing import mainprogram, then wrap those parts of the program in an if block like this:

if __name__ == "__main__":
    # this code will not be run on import
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Wow. Thanks. Also, I put the 'from folder import mainprogram' because at first it didn't let me import the mainprogram, even though it was in the same folder, and when I put the 'from folder' statement before it, it worked. Now for some odd reason, it lets me import it without that 'from' statement. – Justin Aug 10 '13 at 21:45