Значения не возвращаются из основного - PullRequest
0 голосов
/ 24 марта 2020

У меня есть следующий код, который я буду sh извлекать во входной и выходной файлы для дальнейших функций, однако они, похоже, не возвращаются. Все еще довольно новый, поэтому извиняюсь, если это просто.

# PYTHON 3.76 ONLY
# Version 0.0.1

import xml.etree.cElementTree as et
import pandas as pd

import sys, getopt

def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
        print ('test.py -i <inputfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ('test.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    print ('Input file is "', inputfile)
    print ('Output file is "', outputfile)

    return inputfile, outputfile

if __name__ == "__main__":
    main(sys.argv[1:])

# convert XML to dataframe

def xml2df(xml_data):
    tree = et.parse(xml_data)
    print (tree.getroot())
    root = tree.getroot()
    print ("tag=%s, attrib=%s" % (root.tag, root.attrib))

    #iterate over each value for room and each user and add to rows
    rows = []

    for child in root.iter('rooms'):
        roomId, roomTitle = 'id', 'ttl'
    for it in child:
        if it.tag == 'room':
            roomId = it.findtext('roomID')
            roomTitle = it.findtext('roomTitle')
            roomStatus = it.findtext('status')
            isAnonymous = it.findtext('isAnonymous')
        elif it.tag == 'users':
            rows.append([roomId, roomTitle, roomStatus, isAnonymous, it.findtext('uuid'), it.findtext('bbgEmail'),
                it.findtext('corpEmail'), it.findtext('fullName'), it.findtext('firmName'), it.findtext('accountNumber'),
                      it.findtext('city'), it.findtext('accountName'), it.findtext('inviteDate'), it.findtext('removalDate')])

    df = pd.DataFrame(rows, columns=['roomId', 'roomTitle', 'roomStatus', 'isAnonymous', 'uuid', 'bbgEmail', 
                                 'corpMail', 'fullName', 'firmName', 'accountNumber', 'city', 'accountName', 'inviteDate', 'removalDate'])

    return df


df = xml2df(inputfile)
#output to csv
df.to_csv(ooutputfile+".csv", sep=',', index=False)

Возвращена ошибка

Трассировка (последний последний вызов): файл "parse_pChatDump.py", строка 63, в df = xml2df (inputfile) NameError: name 'inputfile 'не определено

1 Ответ

2 голосов
/ 24 марта 2020

Вы создаете inputfile и outputfile в методе main и возвращаете его, НО вы не сохраняете их в переменных, где запускается скрипт, поэтому вы не можете получить к ним доступ позже, выполните:

def main(argv):
    inputfile = ''
    outputfile = ''
    # ...
    return inputfile, outputfile


def xml2df(xml_data):
    # ...
    return df


if __name__ == "__main__":
    inputfile, outputfile = main(sys.argv[1:])
    df = xml2df(inputfile)
    df.to_csv(outputfile + ".csv", sep=',', index=False)
...