3

I want to import a variable from another python file.

This first file runs on the side of file2 on a second window.

File1.py

def onlinecheckext():
global onlinecheckvarr
while 1:
    try:
        onlinecheckscc = pyautogui.locateOnScreen(imPath("start_detect.png"))
        if onlinecheckscc is None:
            logging.debug("I am Online")
            onlinecheckvarr = True
            time.sleep(2)
        else:
            logging.debug("I am not online")
            onlinecheckvarr = False
            time.sleep(2)


    except:
        logging.debug("Online check fail")
        return False 

File2.py

from file1 import onlinecheckvarr
while onlinecheckvarr is True:
    print("TEST")
else:
    print("Test2")

Error : NameError: name 'onlinecheckvarr' is not defined.

I have try almost everything and still didn't get it, it's a global var and i imported it right i think but it still throws errors.

Mehmaam
  • 573
  • 7
  • 22
Soloco
  • 29
  • 2
  • First of all: Did you call `onlinecheckext()` *before* the invokation of File2.py? Otherwise `onlinecheckvarr` is not yet defined yet – l-x Aug 29 '17 at 13:51
  • file1.py runs independet in another window, its only genrating values for file2.py, but its not working right i think, the thoughts behind it is that file1.py checks the stuff and if file1.py fails file2.py can jump to another state. – Soloco Aug 29 '17 at 14:38
  • 1
    I'd guess, you missunderstood the effect of a global variable. "global" does not mean, that you can grap the variable from "anywhere on your computer", it's only global within the script and is absolutely capsuled from other processes. For your purpose you need to place the variable/values somewhere "public", where both processes can read from (e.g. write to a file), which is not so good, though. A very good solution would be, to have the processes communicate via a socket. Btw: a python file does not do anything, it's the interpreter that executes. – Sim Son Oct 17 '17 at 20:50
  • Beside the point, but [a bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341). – wjandrea Dec 15 '19 at 22:35

1 Answers1

-1

It can be done this way:

from file1 import onlinecheckext # <--
while onlinecheckvarr is True:
    print("TEST")
else:
    print("Test2")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Liinge
  • 1
  • 1
    No, `onlinecheckvarr` is still not defined. Even if you ran the function it might not be defined because of the try-except. Anyway I think OP's trying to do something asynchronous but doesn't know what they're doing -- I mean the question is an [XY problem](https://meta.stackexchange.com/q/66377/343832). BTW welcome to Stack Overflow! Check out the [tour]. – wjandrea Dec 15 '19 at 22:37