从其他文件执行脚本

时间:2018-02-23 23:13:22

标签: python

我想知道是否可以将脚本导入/包含在其他脚本中?

在我的情况下,我的主要脚本只询问用户的选择。根据这个选择,我想要包含其他脚本。

print (30 * '-')
print ("   M A I N - M E N U")
print (30 * '-')
print 'Information'
print (30 * '-')
print ("1. Choice 1")
print ("2. Choice 2")
print ("3. Choice 3")
print (30 * '-')

is_valid=0

while not is_valid :
        try :
                choice = int ( raw_input('Enter your choice [1-3] : ') )
                is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
        except ValueError, e :
                print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
if choice == 1:
        # Here I want to include the other script from other file.

1 个答案:

答案 0 :(得分:1)

正如DyZ所说,看看import模块。

作为一个简单示例,假设您具有以下文件夹结构

  • 的src /
    • main.py
    • moduleA /
      • __初始化__。PY
      • menu.py

如果您在src下运行上述代码,则可以在menu.py中导入main.py,如:

  来自moduleA导入菜单的

ps。:可以使用https://docs.python.org/3.3/library/argparse.html

轻松解析参数
相关问题