-1

我有 python 脚本,它正在更新文件中的变量值,变量值是当前被编码的,但它们将在运行时使用命令行参数传递。我的代码如下:

    import subprocess
    import time
    import sys
    import string
    from optparse import OptionParser
    from optparse import OptionGroup
    def main():
        usage = "usage: %prog [options]"
        parser = OptionParser()
        try:
            parser = parse_options(parser)
            (options, args) = parser.parse_args()
        except SystemExit:
            return 0
        myfile = open('over.tex','r')
        data = myfile.readlines()
        myfile.close()
        val = time.strftime("%d/%m/%Y")
        for i in range(len(data)):
            test_dict = dict( var_Title = "ABC doc"
                              , var_Doc = "136"
                              , var_ECN = "XXXX"
                              , var_date = time.strftime("%d/%m/%Y")
                              , var_ProjectName= str(options.project_name)
                              , var_version = str(options.version) )
            test_tuple = ( 'var_Title'
                           , 'var_Doc'
                           , 'var_Rev'
                           , 'var_ECN'
                           , 'var_date'
                           , 'var_ProjectName'
                           , 'var_version'
                           )
            for key in test_tuple:
                print test_dict[key]
                data[i] = data[i].replace((key), (test_dict[key]))                     
        with open('over.tex', 'w') as file:
            file.writelines( data) 
        if options.project_name:
            var = "WELCOME"
        if options.version:
            print "1.1"
    def parse_options(parser):
        group = OptionGroup(parser, "Target options","CMake Target properties")
        group.add_option("", "--project_name", action="store_true",default=False,dest="project_name",help="Project name")
        group.add_option("", "--version", action="store_true",default=False,dest="version",help="Version")
        parser.add_option_group(group)
        return parser

    if __name__ == "__main__":
        main()

现在你可以看到我正在使用 option.parser 将值传递给“var_ProjectName”和“var_version”,但是当我在命令行上执行它时:

myscript.py --project_name --version 

在针对变量 Project_name 和 Project_version 的文件中,我得到如下内容:

Project_name = True
Project_version = True

但这不是我想要的。我想要如下:

Project_name = WELCOME
Project_version = 1.1

那么,请帮助我怎样才能拥有它,我做错了什么?我只想将值从 comandilne 参数传递给所有变量,所以最初我只尝试使用两个变量(project_name 和 version)。

4

1 回答 1

0

而不是action="store_True",指定另一个操作。例如,与

group.add_option(
    "", "--version",
    action="store", dest="version", help="Version")
group.add_option(
    "", "--welcome-project",
    action="store_const", const="WELCOME", dest="project_name",
    help="Project name")

您可以使用参数调用程序--version 1.1 --welcome-project并获取选项

project: "WELCOME"
version: "1.1"
于 2015-12-10T12:17:07.540 回答