yef pie
yef pie

Reputation: 53

How to use a list in other function?

I have a list like this cs_id["CS_A1","CS_b7",...] in a function. At the end of the function the list ist filled with 80 values. How can I use this list (and values) in another function? Here I want to use the list cs_id[] from function unzip in function changecs. (By the way, the second function isn't ready yet.)

Update

I still dont get it....dont know why.

Here is my full code...maybe someone can help.

maker.py

#!/usr/bin/python

import getopt
import sys
import functions as func

ifile = ''
ofile = ''
instances = 0

def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hi:o:n:d", ["help", "ifile=", "ofile=", "NumberOfInstances="])
    except getopt.GetoptError:
        func.usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            func.usage()
            sys.exit()
        elif opt in '-d':
            global _debug
            _debug = 1
        elif opt in ("-i", "--ifile"):
            global ifile
            ifile = arg
        elif opt in ("-o", "--ofile"):
            global ofile
            ofile = arg
        elif opt in ("-n", "--NumberOfInstances"):
            global instances
            instances = int(arg)

    func.unzip(ifile, instances)
    func.changecs()

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

functions.py

import os
import zipfile
import sys
import string
import random

# printing usage of warmaker.py
def usage():
    print "How to use warmaker.py"
    print 'Usage: ' + sys.argv[0] + ' -i <inputfile> -o <outputfile> -n <NumberOfInstances>'

# creating random IDs for CS instance e.g. CS_AE, CS_3B etc.
def id_generator(size=2, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

# unzip the reference warfile and build n instances
def unzip(ifile, instances,):
    newinstance = ifile
    cs_id = []
    for i in xrange(instances):
        cs_id.append('CS_' + id_generator())
        i += 1
    print 'Searching for reference file ' + newinstance
    if os.path.isfile(newinstance):  # check if file exists
        print 'Found ' + newinstance
    else:
        print newinstance + ' not fonund. Try again.'
        sys.exit()
    print 'Building ' + str(instances) + ' instances... '
    for c in xrange(instances):
        extract = zipfile.ZipFile(newinstance)
        extract.extractall(cs_id[c])
        extract.close()
        print cs_id[c] + ' done'
        c += 1
    return cs_id

#def create_war_file():

def changecs(cs_id):
    n = 0
    for item in cs_id:
        cspath = cs_id[n] + '/KGSAdmin_CS/conf/contentserver/contentserver-conf.txt'
        if os.path.isfile(cspath):
            print 'contentserver-conf.txt found'
        else:
            print 'File not found. Try again.'
        sys.exit()
        n += 1
    #f = open(cspath)
    #row = f.read()

Upvotes: 0

Views: 75

Answers (5)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 14674

Two ways.

1/ Return the list in unzip

def unzip(ifile, instances):
    # No need for this global
    # global cs_id 

    cs_id = []
    # Do stuff
    # [...]

    # Return the list
    return cs_id

In this case you can call unzip and get the complete list as return value:

def changecs(instances):

    # The following line is equivalent to
    # cs_id = unzip(ifile, instances) 
    # for c in cs_id:
    for c in unzip(ifile, instances):

        cspath = cs_id + '/abc/myfile.txt'

2/ Pass it as a parameter and modify it in unzip.

def unzip(ifile, instances, cs_id):
    # Do stuff
    # [...]

In this case you can pass unzip the empty list and let it modify it in place:

def changecs(instances):

    cs_id = []

    unzip(ifile, instances, cs_id):

    for c in cs_id:

        cspath = cs_id + '/abc/myfile.txt'

I prefer the first approach. No need to provide unzip with an empty list. The second approach is more suited if you have to call unzip on an existing non-empty list.

Edit:

Since your edit, unzip returns cs_id and changecs uses it as an input.

def unzip(ifile, instances,):
    [...]
    return cs_id

def changecs(cs_id):
    [....]

But you call them like this:

func.unzip(ifile, instances)
func.changecs()  # This should trigger an Exception since changecs expects a positional argument

You should call them like this:

variable = func.unzip(ifile, instances)
func.changecs(variable)

or just

func.changecs(func.unzip(ifile, instances))

Upvotes: 1

RepeatQuotations
RepeatQuotations

Reputation: 724

The code is all but there. At the bottom of def unzip() the array cs_id is being returned using the return command. The returned array can be stored in a variable from the function which runs unzip(). In this case, it's our main python function.

After you have the cs_id array in a variable in your main function, pass it to changecs() like: func.changecs(cs_id)

Edit last two lines of def main(argv) to:

cs_id = func.unzip(ifile, instances)
func.changecs(cs_id)

In the above code, unzip(ifile, instances) returns our array cs_id. We pass this into changecs(cs_id) as an parameter.

Upvotes: 0

th3an0maly
th3an0maly

Reputation: 3510

Make unzip return the value. Call unzip from the main block. Then pass the return value from unzip into changecs. Simple.

def unzip(...):
   ...
   return cs_id

def changecs(cs_id, ...):
   ... do stuff with cs_id ...

if __name__ == "__main__":
   ... main block ... # This can be replaced with any kind of driver code

Alternatively, you can call unzip directly from within changecs (if that flow is permissible).

Upvotes: 0

Luis F Hernandez
Luis F Hernandez

Reputation: 931

you can call the function and return it to the other function. Not sure where you'd want to use it but as an example this is the same concept

def foo():
    l = [1,3,2,5,4,6,5]
    l.append(10)

    return l

def bar():
    l = foo()
    print (l)

return terminates the function and in your case you'd want to put it at the end of the function.

Upvotes: 0

One possibility is to initialize the list outside of the function, then call it in both, i guess.

Upvotes: 0

Related Questions