Search code examples
pythonpython-3.xreplit

Using variables from another Python file & function in module not running?


This is a continuation of my previous question, with more details. (Formatting should be better, as I am on a computer now!)

So I am trying to create a game in Python, where if a number reaches a certain amount you lose. You try to keep the number under control to keep it from reaching the number it shouldn't. Now, I had an error in my previous question that said:

AttributeError: module 'core temp' has no attribute 'ct'

However, I've modified my code a bit and no longer get any errors. However, when I run the code, a function in a module I made won't run.

To make sure that anyone trying to figure out the solution has all the resources they need, I'll provide all my code.

This is the code in the file main.py:

from termcolor import colored
from time import sleep as wait
import clear
from coretemp import ct, corestart

print(colored("Begin program", "blue"))
wait(1)
clear.clear()


def start():
    while True:
        while True:
            cmd = str(input("Core> "))
            if cmd == "help":
                print(
                    "List of commands:\nhelp - Show a list of commands\ntemp - Show the current temperature of the core in °C\ninfo - Show core info\ncool - Show coolant control"
                )
                break
            elif cmd == "temp":
                if ct < 2000:
                    print(
                        colored("Core temperature: " + str(ct) + "°C",
                            "green"))
                elif ct < 4000:
                    print(
                        colored("Core temperature: " + str(ct) + "°C",
                            "yellow"))
                elif ct >= 3000:
                    print(
                        colored("Core temperature: " + str(ct) + "°C", "red"))


print("Welcome to SprinkleLaboratories Main Core System")
wait(1)
print(
    "\nYou have been hired as the new core operator.\nYour job is to maintain the core, and to keep the temperature at a stable number. Or... you could see what happens if you don't..."
)
wait(3)
print("\nTo view available commands, use the \"help\" command!")
cont = input("Press enter to continue> ")
clear.clear()
start()
corestart(10)

This is the code in the file clear.py:

print("clear.py working")

def clear():
print("\n"*100)

This is the code in the file coolant.py:

from time import sleep as wait

print("coolant.py working")

coolam = 100
coolactive = False

def coolact():
    print("Activating coolant...")
    wait(2)
    coolactive = True
    print("Coolant activated. "+coolam+" coolant remaining.")

This is the code in the file coretemp.py:

from coolant import coolactive
from time import sleep as wait
print("coretemp.py working")

ct = 0

def corestart(st):
  global ct
  ct = st
  while True:
    if coolactive == False:
      ct = ct + 1
      print(ct)
      wait(.3)
    else:
      ct = ct - 1
      print(ct)
      wait(1)

Note:

Some of the code in the files are incomplete, so some things may seem like they do nothing at the moment

If you want to see the code itself, here is a link to a repl.it: Core

Note #2:

Sorry if things aren't formatted correctly, if I did something wrong in the question, etc. I'm fairly new to asking questions on Stackoverflow!


Solution

  • You can't normally have two things running at once, so when you are in the while True of start() you never ever get to the next bit of your code because while True is true forver.

    So, threading to the rescue! Threads allow you to have one thing going on in one place and another thing going on in another. If we put the code to update and print the temperature in its own thread, we can set that running and then go ahead and start doing the infinite loop in start() while our thread keeps running in the background.

    One other note, you should be importing coretemp itself, rather than importing variables from coretemp, otherwise you will be using a copy of the variable ct in main.py when you actually want to be using the real value of ct from coretemp.

    Anyhow, here's a minimal update to your code that shows the use of threads.

    main.py:

    from termcolor import colored
    from time import sleep as wait
    import clear
    import coretemp
    import threading
    
    print(colored("Begin program", "blue"))
    wait(1)
    clear.clear()
    
    
    def start():
        while True:
            while True:
                cmd = str(input("Core> "))
                if cmd == "help":
                    print(
                        "List of commands:\nhelp - Show a list of commands\ntemp - Show the current temperature of the core in °C\ninfo - Show core info\ncool - Show coolant control"
                    )
                    break
                elif cmd == "temp":
                    if coretemp.ct < 2000:
                        print(
                            colored("Core temperature: " + str(coretemp.ct) + "°C",
                                    "green"))
                    elif coretemp.ct < 4000:
                        print(
                            colored("Core temperature: " + str(coretemp.ct) + "°C",
                                    "yellow"))
                    elif coretemp.ct >= 3000:
                        print(
                            colored("Core temperature: " + str(coretemp.ct) + "°C", "red"))
    
    
    
    print("Welcome to SprinkleLaboratories Main Core System")
    wait(1)
    print(
        "\nYou have been hired as the new core operator.\nYour job is to maintain the core, and to keep the temperature at a stable number. Or... you could see what happens if you don't..."
    )
    wait(3)
    print("\nTo view available commands, use the \"help\" command!")
    cont = input("Press enter to continue> ")
    clear.clear()
    coretemp.corestart(10)
    t1 = threading.Thread(target=coretemp.coreactive)
    t1.start()
    start()
    

    coretemp.py:

    from coolant import coolactive
    from time import sleep as wait
    
    print("coretemp.py working")
    
    ct = 0
    
    def corestart(st):
      global ct
      ct = st
    
    def coreactive():
      global ct
      while True:
        if coolactive == False:
          ct = ct + 1
          print(ct)
          wait(.3)
        else:
          ct = ct - 1
          print(ct)
          wait(1)
    

    You can see we still have some work to do to make the output look nice and so on, but hopefully you get the general idea.