Использование переменных из другого файла и функции Python в модуле не работает?
Это продолжение моего предыдущего вопроса, с более подробной информацией. (Форматирование должно быть лучше, так как я сейчас на компьютере!)
Поэтому я пытаюсь создать игру на Python, в которой, если число достигает определенной суммы, вы теряете. Вы пытаетесь держать номер под контролем, чтобы он не достиг того числа, которого не должно быть. Теперь у меня была ошибка в моем предыдущем вопросе, который сказал:
AttributeError: модуль 'core temp' не имеет атрибута 'ct'
Тем не менее, я немного изменил свой код и больше не получаю никаких ошибок. Однако, когда я запускаю код, функция в модуле, который я сделал, не будет работать.
Чтобы убедиться, что у любого, кто пытается выяснить решение, есть все необходимые ресурсы, я предоставлю весь свой код.
Это код в файле 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)
Это код в файле clear.py
:
print("clear.py working")
def clear():
print("\n"*100)
Это код в файле 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.")
Это код в файле 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)
Замечания:
Часть кода в файлах неполная, поэтому некоторые вещи могут показаться, что в данный момент они ничего не делают
Если вы хотите увидеть сам код, вот ссылка на repl.it: Core
Заметка 2:
Извините, если что-то неправильно отформатировано, если я что-то не так сделал в вопросе и т. Д. Я довольно новичок в задании вопросов по Stackru!
1 ответ
Обычно вы не можете запустить две вещи одновременно, поэтому, когда вы находитесь в while True
из start()
Вы никогда не получите следующий бит вашего кода, потому что while True
верно навсегда.
Итак, нить на помощь! Потоки позволяют вам иметь одно дело в одном месте, а другое - в другом. Если мы поместим код для обновления и напечатаем температуру в своем собственном потоке, мы можем установить этот режим, а затем продолжить и начать делать бесконечный цикл в start()
в то время как наш поток продолжает работать в фоновом режиме.
Еще одно примечание, вы должны импортировать coretemp
сам, а не импортировать переменные из coretemp
в противном случае вы будете использовать копию переменной ct
в main.py
когда вы на самом деле хотите использовать реальную стоимость ct
от coretemp
,
В любом случае, вот минимальное обновление вашего кода, которое показывает использование потоков.
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)
Вы можете видеть, что у нас еще есть работа, чтобы сделать вывод красивым и так далее, но, надеюсь, вы поймете общую идею.