【发布时间】:2021-08-05 18:53:45
【问题描述】:
我有几个脚本。在应用程序的主脚本中,我创建了一个带有答案的文本文档 (123.txt)。
另外,我正在创建另一个带有时间表的文本文件 (test_schedule.txt)。从这个时间表中,我将 2 个参数 (.do(test_func, 123)) 传递给在主应用程序关闭后运行的脚本 (test_schedule.py)。
我就是想不通我做错了什么。如果我写
exec(open(f"./test_schedule.py").read())
在关闭应用程序之前 (Test().stop())
然后我得到一个错误: NameError: name 'schedule' 没有定义
如果我写 exec(open(f"./test_schedule.py").read())
关闭应用程序后 (Test().stop())
然后计划任务工作,但应用程序窗口没有关闭并且没有响应。 谁能告诉我我做错了什么?
这是我的主要应用程序代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.uix.label import Label
from datetime import datetime
from datetime import timedelta
now = datetime.now()
Window.size = (240, 480)
Window.clearcolor = (180 / 255, 90 / 255, 3 / 255, 1)
Window.title = "Test"
class Setup(Screen):
def __init__(self, **kw):
super(Setup, self).__init__(**kw)
my_list = ['red', 'green', 'yellow', 'blue', 'white', 'magenta', 'cian']
grid = GridLayout(cols=1, padding=10, spacing=3)
label = Label(text=f'{my_list}', size_hint=(1, None), halign="left", valign="middle")
label.bind(size=label.setter('text_size'))
grid.add_widget(label)
grid.add_widget(
Button(text='submit', background_color=(0, 1, 1, 1), pos_hint=(None, 1), size_hint_y=None,
height=60,
on_press=lambda x: self.on_stop(my_list)))
self.add_widget(grid)
def on_stop(self, x):
with open('123.txt', 'w', encoding="utf-8") as test: # text file with answers
print(f'{x}', file=test)
created_at = datetime.now()
time_change = timedelta(minutes=1)
new_time = created_at + time_change # time set to current time + 1 minute
print(new_time.strftime("%H:%M"))
with open('schedule_list_test.txt', 'w', encoding="utf-8") as schedule: # text file with schedule
print(f'schedule.every().day.at("{new_time.strftime("%H:%M")}").do(test_func, 123)', file=schedule)
# exec(open(f"./test_schedule.py").read()) # if I place here I get error
Test().stop()
sm = ScreenManager()
sm.add_widget(Setup(name='setup'))
class Test(App):
def __init__(self, **kvargs):
super(Test, self).__init__(**kvargs)
def build(self):
return sm
if __name__ == '__main__':
Test().run()
exec(open(f"./test_schedule.py").read()) # if I place here app window is not responding
这是在主脚本之后运行的脚本 (test_schedule.py):
import schedule
import time
import sys
class Scheduler:
my_list = None
with open("schedule_list_test.txt", "r", encoding="utf-8") as s_list:
line = s_list.readline()
a = line.strip('\n')
my_list = a
def __init__(self):
exec(self.my_list)
while True:
schedule.run_pending()
time.sleep(1)
def test_func(x):
sys.argv = ["./test_run.py", x]
return exec(open(f"./test_run.py").read())
scheduler = Scheduler()
这里是脚本 (test_run.py),用于从带有答案的文本文件中打印答案:
from sys import argv
script_name, execute = argv
with open(f"{execute}.txt", "r", encoding="utf-8") as q_list:
content = q_list.readline()
print(content)
抱歉,我是编程新手,我的代码可能看起来很糟糕。 提前感谢您的帮助!
【问题讨论】: