【问题标题】:Can't pass values via command line无法通过命令行传递值
【发布时间】:2015-05-14 04:15:14
【问题描述】:

我必须编写一个程序来读取文件并将一些分析写入文本文件。该程序必须通过命令行获取一些信息,但我看不到,即使给定模板也无法弄清楚。我编写了一个测试程序,看看我是否可以成功地将命令行输入传递给类。

#!/usr/bin/env python3

########################################################################
# CommandLine
########################################################################
class CommandLine() :
    '''
    Handle the command line, usage and help requests.

    CommandLine uses argparse, now standard in 2.7 and beyond. 
    it implements a standard command line argument parser with various argument options,
    a standard usage and help, and an error termination mechanism do-usage_and_die.

    attributes:
    all arguments received from the commandline using .add_argument will be
    avalable within the .args attribute of object instantiated from CommandLine.
    For example, if myCommandLine is an object of the class, and requiredbool was
    set as an option using add_argument, then myCommandLine.args.requiredbool will
    name that option.

    '''

    def __init__(self, inOpts=None) :
        '''
        CommandLine constructor.
        Implements a parser to interpret the command line argv string using argparse.
        '''

        import argparse
        self.parser = argparse.ArgumentParser(description = 'Program prolog - a brief description of what this thing does', 
                                             epilog = 'Program epilog - some other stuff you feel compelled to say', 
                                             add_help = True, #default is True 
                                             prefix_chars = '-', 
                                             usage = '%(prog)s [options] -option1[default] <input >output'
                                             )
        self.parser.add_argument('inFile', action = 'store', help='input file name')
        self.parser.add_argument('outFile', action = 'store', help='output file name') 
        self.parser.add_argument('-lG', '--longestGene', action = 'store', nargs='?', const=True, default=True, help='longest Gene in an ORF')
        self.parser.add_argument('-mG', '--minGene', type=int, choices= range(0, 2000), action = 'store', help='minimum Gene length')
        self.parser.add_argument('-s', '--start', action = 'append', nargs='?', help='start Codon') #allows multiple list options
        self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')  
        if inOpts is None :
            self.args = self.parser.parse_args()
        else :
            self.args = self.parser.parse_args(inOpts)

########################################################################
#MAIN GOES HERE
########################################################################


def main(myCommandLine=None):
    '''
    Implements the Usage exception handler that can be raised from anywhere in process.  

    '''

    myCommandLine = CommandLine(myCommandLine)

        #myCommandLine.args.inFile #has the input file name
        #myCommandLine.args.outFile #has the output file name
        #myCommandLine.args.longestGene #is True if only the longest Gene is desired
        #myCommandLine.args.start #is a list of start codons
        #myCommandLine.args.minGene #is the minimum Gene length to include

    print (myCommandLine.args) # print the parsed argument string .. as there is nothing better to do

    if myCommandLine.args.longestGene:
        print ('longestGene is', str(myCommandLine.args.longestGene) )
    else :
        pass
    class Test:
        def __init__(self):
            print(myCommandLine.args.minGene)

if __name__ == "__main__":
    main()

class Test:
    def __init__(self):
        self.test()

    def test(self, infile = myCommandLine.args.inFile, outfile = myCommandLine.args.outFile, longest = myCommandLine.args.longestGene, start = myCommandLine.args.start, min = myCommandLine.args.minGene):
        print(infile)
        print(outfile)
        print(longest)
        print(start)
        print(min)

new_obj = Test()

命令行输入应如下所示:python testcommand.py -minG 100 -longestG -starts ATG tass2ORFdata-ATG-100.txt

据说主程序运行到它说“MAIN GOES HERE”的地方,但是当我尝试时,我得到了一个错误“myCommandline is not defined”。所以我把程序移到了最后。但我收到错误“'>' 运算符保留供将来使用”

如果这很重要,我正在使用 Powershell。如何将这些数据输入到我的课堂中?

【问题讨论】:

  • 把parser.parse_args()的结果传给你类的构造函数?

标签: python powershell python-3.x command-line


【解决方案1】:

您不需要 CommandLine 类。正如詹姆斯米尔斯所建议的,这里有一个例子:

import argparse

class Test:
    def __init__(self, infile, outfile, longest, start, min):
        self.infile = infile
        self.test()

    def test(self):
        print(self.infile)

def main():
    parser = argparse.ArgumentParser(description = 'Program prolog', 
                                     epilog = 'Program epilog', 
                                     add_help = True, #default is True 
                                     prefix_chars = '-', 
                                     usage = 'xxx')
    parser.add_argument('-i', '--inFile', action = 'store', help='input file name')
    parser.add_argument('-o', '--outFile', action = 'store', help='output file name') 
    parser.add_argument('-lG', '--longestGene', action = 'store', nargs='?', const=True, default=True, help='longest Gene in an ORF')
    parser.add_argument('-mG', '--minGene', type=int, choices= range(0, 20), action = 'store', help='minimum Gene length')
    parser.add_argument('-s', '--start', action = 'append', nargs='?', help='start Codon') #allows multiple list options
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')  
    args = parser.parse_args()
    test = Test(args.inFile, args.outFile, args.longestGene, args.minGene, args.start)

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2014-10-17
    • 2014-11-05
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多