简体   繁体   English

使用模块中另一个Python文件和函数的变量未运行?

[英]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. 因此,我尝试使用Python创建游戏,如果数字达到一定数量,您将会输掉游戏。 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' AttributeError:模块“核心温度”没有属性“ 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 : 这是文件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 : 这是文件clear.py的代码:

print("clear.py working")

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

This is the code in the file coolant.py : 这是文件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 : 这是文件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 如果您想查看代码本身,请参见以下链接:repl.it: 核心

Note #2: 笔记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! 抱歉,如果格式化不正确,或者我在问题中做错了什么,等等。对于在Stackoverflow上提问,我还是很陌生!

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. 通常,您无法一次运行两件事,所以当您在start() while Truestart()您永远都不会到达代码的下一部分,因为while True永远都是true。

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. 如果我们在自己的线程中放置代码来更新和打印温度,则可以设置运行状态,然后继续运行,并在start()start()无限循环,同时线程继续在后台运行。

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 . 另一个注意事项,您应该导入coretemp本身,而不是从coretemp导入变量,否则,当您实际上想从coretemp使用ct的实际值时,将在main.py使用变量ct的副本。

Anyhow, here's a minimal update to your code that shows the use of threads. 无论如何,这是代码的最小更新,显示了线程的使用。

main.py : 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 : 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. 您可以看到我们还有很多工作要做,以使输出看起来不错,依此类推,但希望您能大致理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM