0

目前我的程序工作如下:

    argparse.py -i file.csv -o newfile.xml -x

其中 argparse.py 是程序的名称,-i 表示输入文件,即 file.csv,-o 是输出文件,称为 newfile.xml,-x 是调用时的操作参数, 将以下 csv 文件转换为 xml 文件。但是,我正在尝试编辑我的程序,以便在命令提示符下,您所要做的就是输入:

    argparse.py file.csv newfile.xml

它会自动将其转换为没有 -x 或 -i 或 -o 的 xml 文件。这是我的代码:

import os
import sys
import argparse
import csv
import indent
from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment, tostring

def get_args(args):
    parser=argparse.ArgumentParser(description='Convert wordlist text files to various formats.', prog='Text Converter')
    parser.add_argument('-v','--verbose',action='store_true',dest='verbose',help='Increases messages being printed to stdout')
    parser.add_argument('-c','--csv',action='store_true',dest='readcsv',help='Reads CSV file and converts to XML file with same name')
    parser.add_argument('-x','--xml',action='store_true',dest='toxml',help='Convert CSV to XML with different name')      
    parser.add_argument('inputfile',type=str,help='Name of file to be imported')
    parser.add_argument('outputfile',help='(optional) Output file name',nargs='?')
    args = parser.parse_args()
    if not (args.toxml or args.readcsv):
        parser.error('No action requested')
        return None
    if args.outputfile is None:
        args.outputfile = os.path.splitext(args.inputfile)[0] + '.xml'
    return args

def main(argv):
    args = get_args(argv[1:])
    if args is None:
        return 1
    inputfile = open(args.inputfile, 'r')
    outputfile = open(args.outputfile, 'w')
    reader = read_csv(inputfile)
    if args.verbose:
        print ('Verbose Selected')
    if args.toxml:
        if args.verbose:
            print ('Convert to XML Selected')
        generate_xml(reader, outputfile)
    if args.readcsv:
        if args.verbose:
            print ('Reading CSV file')
    return 1 # you probably want to return 0 on success

def read_csv(inputfile):
      return list(csv.reader(inputfile))

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
            x1,y1,z1,x2,y2,z2,cost = row
            if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
                toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
                cost = SubElement(current_group, 'cost',{'':cost})
        i+=1
    indent.indent(root)
    tree.write(outfile)

if (__name__ == "__main__"):
    sys.exit(main(sys.argv))

我想也许我应该检查每个参数的位置或类似的东西,但是我如何将它纳入,因为我是 python 新手

4

1 回答 1

0

你只需要

import argparse
p = argparse.ArgumentParser()
p.add_argument('input_file')
p.add_argument('output_file')
args = p.parse_args()

# With read_csv and generate_xml defined as above
reader = read_csv(args.input_file)
generate_xml(reader, args.output_file)
于 2013-06-16T19:26:15.967 回答