I'm making a game engine that can be used with multiple story modules. I want to keep the stories in a subdirectory and use a single PLAY.py
file to allow the user to choose one of them.
So far, I have been able to use this simple code to get a list of all of the story modules:
import glob
stories = glob.glob( ./stories/ds_*.py )
I then use a for loop and a format statement to list the options for the user. The problem is that I can't find out how to use the resulting strings to actually import anything. Maybe glob is not the best solution?
答案 0 :(得分:2)
只需列出stories目录中的文件,然后打开用户选择的文件:
from os import listdir
from os.path import isfile, join
import imp
stories_path = 'path/to/modules'
# Put in stories all the modules found:
stories = [f for f in listdir(stories_path ) if isfile(join(stories_path,f))]
# Let the user select one...
selected = stories[xx]
# Import it:
story = imp.load_source('module.name', selected)