-2

I made 2 programs for show porpose. I would like to import the global variable from the transmitter function into another file, yet the problem that I encounter is that the While true loop also comes along spoiling my whole second program, because the second problem now also starts to show the itiration.

Program 1:

import time

def transmitter():
    global temp

global temp
temp = 2

transmitter()

while True: # a random task just to see if I only imported the function
    x = 0
    print(x + 1)
    time.sleep(0.2)

Program 2:

from transmitguy import transmitter

def valuepullup():
    newval = transmitguy.transmitter()
    print(newval)

valuepullup()

I only need my second program to show the value of 2 once. (2 is the globalvar from file 1)

Anton van der Wel
  • 451
  • 1
  • 6
  • 20

1 Answers1

1

The short answer is that you can't get only one piece of a module. from x import y imports x in the same way import x does. The only difference is that, in the former case, y is added to your current global namespace, and in the latter case, x is. The docs for import say:

The from form ... find[s] the module specified in the from clause, loading and initializing it if necessary ...

I am not sure exactly what you are trying to accomplish. As the commenters noted, you can check for __main__. However, you might do better to put your variable in its own module, then import that module from both of your existing modules.

See also the tutorial.

cxw
  • 16,685
  • 2
  • 45
  • 81