Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How to import many modules to main and execute

once again am a newbie to python. I have this assignment that involves searching for details of a certain club by entering the name of a club or asking a keyword such as Arsenal score etc. I have made several modules modules for several teams as follows:

The closest I came to main is this:

def main():
    import team que1

if __name__ =='__main__':main()

I also have other modules for other teams such as NBA, Hockey,Rugby etc. Every time I run the module separately, it works, but I need a way to import into a main to allow a user to enter any key word such as 'Chicago Bulls players' and the module runs or 'Arsenal score' and the module runs from the main. The modules contain quite a long detail and that is why I have separated the long code into these modules. I have also put them into packages.Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is small snippet to make you understand:

  1. In python you can import module by passing module name as string. __import__

  2. two script in my snippet:

2.1 main script name is menu.py.

2.2 module name is arsenal which will load based on your input string:

You can extend the main script and module, the way you like. this is just for understanding.

main.py

#!/usr/bin/python

def load_module(name):
    return __import__(name)

def what_score(module_name, sc):
    return getattr(module_name, 'score')(sc)

if __name__ == '__main__':
    print "Input team name: ",
    team_name = raw_input().strip()
    module_name = load_module(team_name)
    print what_score(module_name, 5)

arsenal.py

def score(n):
    return 'Score from [%s] is %d' % (__name__, n)

Output:

:tmp:> python menu.py
Input team name:  arsenal
Score from [arsenal] is 5
:tmp:>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...