将Python脚本化模块组合成单个模块,以便在命令行上多用

将Python脚本化模块组合成单个模块,以便在命令行上多用,python,function,command-line,import,Python,Function,Command Line,Import,我有三个python中的命令行脚本,它们也在这个其他模块中使用 #gather.py import script1 import script2 import script3 这三个模块可以通过以下选项从命令行调用: script1 has options a,b,c,d script2 has options e,f,g,h script3 has options i,j,k,l 单独调用script1、2或3时,使用 python script1.py name_of_a_fi

我有三个python中的命令行脚本,它们也在这个其他模块中使用

#gather.py
import script1
import script2
import script3
这三个模块可以通过以下选项从命令行调用:

script1 has options a,b,c,d  
script2 has options e,f,g,h  
script3 has options i,j,k,l 
单独调用script1、2或3时,使用

python script1.py name_of_a_file a
例如,执行选项“a”。这同样适用于其他脚本

但是,使用gather.py脚本,我键入:

python gather.py name_of_a_file a(or b, c,...or l)
有时执行该选项,有时不执行(有时会出现错误
ImportError:cannotimportname函数\u on_script1


很明显,无论选择哪个选项,都会执行所有脚本,是否有方法仅执行属于所选选项的脚本

您需要在gather.py中添加一些控制逻辑和参数解析,以便根据输入字符串执行正确的模块。让我们使用集合为我们完成大部分工作:

import sys

command_line_options = {'script1.py': set(['a','b','c','d']),
                        'script2.py': set(['d','e','f','g']),
                        'script3.py': set(['h','i','j','k'])}

user_input = sys.argv
file_name = user_input[1]
options = user_input[2:]
set_options = set(options)

execute = None
run_options = None
invalid = None

for script, options in command_line_options.iteritems()
    if set_options.issubset(options):
        execute = script
        run_options = list(set_options)
        break
    elif set_options.intersection(options):
        execute = script
        run_options = list(set_options.intersection(options))
        invalid = list(set_options.difference(options))
        break

if not execute:
    print "Input options were not recognized!:", options
    sys.exit()
elif invalid:
    print "Some input options were not recognized:", invalid

sys.argv[2:] = run_options
execfile(execute)

参数解析已经存在于每个脚本中,这就是为什么当我键入a_文件a(或b、c……或l)的python gather.py name_时,会执行所选的选项,但我希望属于该选项的脚本是唯一执行的脚本,而不是所有脚本scripts@carla在我看来,这真的不是最好的做法(主要是因为我假设您的模块在导入时运行,而不是设置为我们可以从导入中调用的类或函数)。但是我已经更新了我的答案,以满足您的要求。