如何根据输入值从不同的起点运行脚本?

  • 本文关键字:起点 运行 脚本 何根 python oop
  • 更新时间 :
  • 英文 :


所以我正在用python创建一个实验,其中有几个任务。我想创建一个函数,如果实验中途退出,可以从不同的起点开始实验,例如,在2个任务之后,我希望它从第三个任务开始。

当run函数(对于整个实验)被调用时,你可以传递'restart=True',然后调用一个重启函数:

def __init__(self, portname, restart=False):
self.__port_name = portname
self.__path = '/Users/emilia/Documents/Dementia task piloting/Lumo'
self.__restart = restart
def __restart(self):
if self.__restart:
restart_point = {'Task to restart from': ''}
dlg = gui.DlgFromDict(dictionary=restart_point, sortKeys=False, title='Where do you want to restart from?')
if not dlg.OK:
print("User pressed 'Cancel'!")
core.quit()
return restart_point['Task to restart from']
else:
return None
def run(self):
start_point = self.__restart()
if start_point:  # TODO: how to run from start point
pass
else: # Run tasks
auditory_exp = self.__auditory_staircase(5)
object_recognition_exp = self.__object_recognition()
self.__resting_state()
simple_motor_exp = self.__simple_motor_task()
naturalistic_motor_exp = self.__naturalistic_motor_task()
self.__end_all_experiment()

在调用所有任务的最后一个运行函数中(这里没有显示这些任务的函数),我如何让它跳转到应该restart=True的对话框中输入的任务名?谢谢你!

由于所有任务随后都会被调用,因此一种简单的方法是将任务放在列表中并遍历它:

import random
class Experiment:
def auditory_staircase(self, i: int):
print(f"Run: Auditory Staircase (i: {i})")
def object_recognition(self):
print(f"Run: Object Recognition")
def resting_state(self):
print(f"Run: Resting State")
def load(self, taskname: str):
# If you need to load previous results
print(f"Load: {taskname}")
def restart(self):
""" Selects a random start point """
return random.choice([None, "Auditory Staircase", "Object Recognition", "Resting State"])
def run(self): 
# List of the tasks with function, arguments and keyword-arguments
tasks = [
("Auditory Staircase", self.auditory_staircase, [5], {}),
("Object Recognition", self.object_recognition, [], {}),
("Resting State", self.resting_state, [], {}),
]
start_from = self.restart()
print(f"restart() returned: {start_from}")
if start_from == None:
start_from = tasks[0][0]
# Iterate over the tasks, and either load previous result or start them
started = False
for taskname, fn, args, kwargs in tasks:
if taskname == start_from:
started = True
if started:
fn(*args, **kwargs)
else:
self.load(taskname)

# Run 10 experiments
e = Experiment()
for i in range(10):
print(f"---- Run {i} ----")
e.run()
print("")

这段代码运行10个不同的实验,每个实验都有一个随机的start_point。输出如下所示:

---- Run 0 ----
restart() returned: Auditory Staircase
Run: Auditory Staircase (i: 5)
Run: Object Recognition
Run: Resting State
---- Run 1 ----
restart() returned: Resting State
Load: Auditory Staircase
Load: Object Recognition
Run: Resting State
---- Run 2 ----
restart() returned: None
Run: Auditory Staircase (i: 5)
Run: Object Recognition
Run: Resting State
...

我包含了一些代码来加载前一次运行的结果。如果不需要,当然可以跳过。

最新更新