【问题标题】:Combining Python scripted modules into a single module for multi use on the command line将 Python 脚本模块组合成一个模块,以便在命令行上多用途
【发布时间】:2014-08-07 14:50:12
【问题描述】:

我在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: cannot import name function_on_script1

很明显,无论选择哪个选项,都会执行所有脚本,有没有办法只执行属于所选选项的脚本?

【问题讨论】:

    标签: python function command-line import


    【解决方案1】:

    您需要在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)
    

    【讨论】:

    • 参数解析已经在每个脚本中,这就是为什么当我输入 python gather.py name_of_a_file a(或 b,c,...或 l)时,选择的选项被执行,但我会就像属于该选项的脚本是唯一执行的脚本,而不是所有脚本
    • @carla 在我看来这确实不是最佳实践(主要是因为我假设您的模块在您导入它们时运行,而不是设置为我们可以从导入中调用的类或函数) .但我已经更新了我的答案来满足你的要求。
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-07-17
    • 2018-04-01
    • 2013-11-11
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多